Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- case AES_GCM:
- {
- // derive HKey as key-dependent encryption of a block of 0's
- uint8_t hkey[AES_BLOCK_SIZE] = {0};
- uint8_t auth_tag[AES_BLOCK_SIZE] = {0};
- uint8_t tmp_block[AES_BLOCK_SIZE];
- uint8_t final_auth_iv[AES_BLOCK_SIZE];
- // encrypt 0 block to auth_tag
- aes_encrypt_block(hkey, hkey, ctx);
- // encrypt counter 0 to final_auth_iv
- aes_encrypt_block(iv, final_auth_iv, ctx);
- increment_iv(iv, ctx->mode.ctr.counter_pos_start, ctx->mode.ctr.counter_len);
- // assoc_data and encrypted_data blocks are zero-padded in GCM
- size_t assoc_data_blocks = ctx->gcm.assoc_data_len/AES_BLOCK_SIZE;
- if(ctx->gcm.assoc_data_len%AES_BLOCK_SIZE) assoc_data_blocks++;
- uint8_t *assoc_data = ctx->gcm.assoc_data_addr;
- size_t encrypted_data_blocks = in_len/AES_BLOCK_SIZE;
- if(in_len%AES_BLOCK_SIZE) encrypted_data_blocks++;
- // start to authenticate the associated data
- for(int idx = 0; idx < assoc_data_blocks; idx++){
- bytes_to_copy = MIN(AES_BLOCK_SIZE, ctx->gcm.assoc_data_len - (idx * AES_BLOCK_SIZE));
- memcpy(tmp_block, assoc_data, bytes_to_copy);
- memset(&tmp_block[bytes_to_copy], 0, AES_BLOCK_SIZE-bytes_to_copy);
- xor_buf(tmp_block, auth_tag, AES_BLOCK_SIZE);
- aes_gf2mul(auth_tag, hkey);
- }
- for(int idx = 0; idx < encrypted_data_blocks; idx++){
- bytes_to_copy = MIN(AES_BLOCK_SIZE, in_len - (idx * AES_BLOCK_SIZE));
- // encrypt block
- memcpy(&out[idx*AES_BLOCK_SIZE], &in[idx*AES_BLOCK_SIZE], bytes_to_copy);
- memset(&out[idx*AES_BLOCK_SIZE+bytes_to_copy], 0, AES_BLOCK_SIZE-bytes_to_copy);
- aes_encrypt_block(iv, buf, ctx);
- xor_buf(buf, &out[idx*AES_BLOCK_SIZE], AES_BLOCK_SIZE);
- // update auth tag for block
- xor_buf(&out[idx*AES_BLOCK_SIZE], auth_tag, AES_BLOCK_SIZE);
- aes_gf2mul(auth_tag, hkey);
- increment_iv(iv, ctx->mode.ctr.counter_pos_start, ctx->mode.ctr.counter_len);
- }
- // compute bit-len of assoc and encrypted
- uint64_t *bitlen = tmp_block;
- *bitlen = ctx->gcm.assoc_data_len * 8;
- bitlen = &tmp_block[8];
- *bitlen = in_len * 8;
- // xor bitlen into auth_tag
- xor_buf(tmp_block, auth_tag, AES_BLOCK_SIZE);
- aes_gf2mul(auth_tag, hkey);
- // encrypt auth tag
- xor_buf(final_auth_iv, auth_tag, AES_BLOCK_SIZE);
- // copy auth tag to last block of ciphertext
- memcpy(&out[idx*AES_BLOCK_SIZE], auth_tag, AES_BLOCK_SIZE);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement