Advertisement
AnthonyCagliano

Untitled

Mar 27th, 2023
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. case AES_GCM:
  2. {
  3. // derive HKey as key-dependent encryption of a block of 0's
  4. uint8_t hkey[AES_BLOCK_SIZE] = {0};
  5. uint8_t auth_tag[AES_BLOCK_SIZE] = {0};
  6. uint8_t tmp_block[AES_BLOCK_SIZE];
  7. uint8_t final_auth_iv[AES_BLOCK_SIZE];
  8.  
  9. // encrypt 0 block to auth_tag
  10. aes_encrypt_block(hkey, hkey, ctx);
  11. // encrypt counter 0 to final_auth_iv
  12. aes_encrypt_block(iv, final_auth_iv, ctx);
  13. increment_iv(iv, ctx->mode.ctr.counter_pos_start, ctx->mode.ctr.counter_len);
  14.  
  15. // assoc_data and encrypted_data blocks are zero-padded in GCM
  16. size_t assoc_data_blocks = ctx->gcm.assoc_data_len/AES_BLOCK_SIZE;
  17. if(ctx->gcm.assoc_data_len%AES_BLOCK_SIZE) assoc_data_blocks++;
  18. uint8_t *assoc_data = ctx->gcm.assoc_data_addr;
  19. size_t encrypted_data_blocks = in_len/AES_BLOCK_SIZE;
  20. if(in_len%AES_BLOCK_SIZE) encrypted_data_blocks++;
  21. // start to authenticate the associated data
  22. for(int idx = 0; idx < assoc_data_blocks; idx++){
  23. bytes_to_copy = MIN(AES_BLOCK_SIZE, ctx->gcm.assoc_data_len - (idx * AES_BLOCK_SIZE));
  24. memcpy(tmp_block, assoc_data, bytes_to_copy);
  25. memset(&tmp_block[bytes_to_copy], 0, AES_BLOCK_SIZE-bytes_to_copy);
  26. xor_buf(tmp_block, auth_tag, AES_BLOCK_SIZE);
  27. aes_gf2mul(auth_tag, hkey);
  28. }
  29.  
  30. for(int idx = 0; idx < encrypted_data_blocks; idx++){
  31. bytes_to_copy = MIN(AES_BLOCK_SIZE, in_len - (idx * AES_BLOCK_SIZE));
  32.  
  33. // encrypt block
  34. memcpy(&out[idx*AES_BLOCK_SIZE], &in[idx*AES_BLOCK_SIZE], bytes_to_copy);
  35. memset(&out[idx*AES_BLOCK_SIZE+bytes_to_copy], 0, AES_BLOCK_SIZE-bytes_to_copy);
  36. aes_encrypt_block(iv, buf, ctx);
  37. xor_buf(buf, &out[idx*AES_BLOCK_SIZE], AES_BLOCK_SIZE);
  38.  
  39. // update auth tag for block
  40. xor_buf(&out[idx*AES_BLOCK_SIZE], auth_tag, AES_BLOCK_SIZE);
  41. aes_gf2mul(auth_tag, hkey);
  42.  
  43. increment_iv(iv, ctx->mode.ctr.counter_pos_start, ctx->mode.ctr.counter_len);
  44. }
  45.  
  46. // compute bit-len of assoc and encrypted
  47. uint64_t *bitlen = tmp_block;
  48. *bitlen = ctx->gcm.assoc_data_len * 8;
  49. bitlen = &tmp_block[8];
  50. *bitlen = in_len * 8;
  51.  
  52. // xor bitlen into auth_tag
  53. xor_buf(tmp_block, auth_tag, AES_BLOCK_SIZE);
  54. aes_gf2mul(auth_tag, hkey);
  55.  
  56. // encrypt auth tag
  57. xor_buf(final_auth_iv, auth_tag, AES_BLOCK_SIZE);
  58.  
  59. // copy auth tag to last block of ciphertext
  60. memcpy(&out[idx*AES_BLOCK_SIZE], auth_tag, AES_BLOCK_SIZE);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement