Advertisement
AnthonyCagliano

Untitled

Apr 1st, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. // internal supporting struct for gcm
  2. typedef struct _aes_gcm {
  3. uint8_t last_block_stop;
  4. uint8_t last_block[16];
  5. uint8_t ghash_key[16];
  6. uint8_t aad_cache[16];
  7. uint8_t aad_cache_len;
  8. size_t aad_len;
  9. uint8_t auth_tag[16];
  10. uint8_t auth_digest[16];
  11. } aes_gcm_t;
  12.  
  13.  
  14. #define ghash_start(buf) memset((buf), 0, 16)
  15.  
  16. void ghash(aes_ctx *ctx, uint8_t *out_buf, const uint8_t *data, size_t len)
  17. {
  18. uint8_t tbuf[AES_BLOCK_SIZE];
  19. size_t data_offset = 0;
  20.  
  21. // the cache allows for incomplete blocks to be queued
  22. // the next call to update will concat the queue and new aad
  23. if(ctx->mode.gcm.aad_cache_len){
  24. size_t cache_len = ctx->mode.gcm.aad_cache_len;
  25. data_offset = MIN(len, AES_BLOCK_SIZE - cache_len);
  26. if(data_offset + cache_len < AES_BLOCK_SIZE){
  27. // if new aad is not enough to fill a block, update queue and stop w/o processing
  28. memcpy(&ctx->mode.gcm.aad_cache[cache_len], data, data_offset);
  29. ctx->mode.gcm.aad_cache_len += data_offset;
  30. return;
  31. }
  32. else {
  33. // if new aad is enough to fill a block, concat queue and rest of block from aad
  34. // then update hash
  35. memcpy(tbuf, ctx->mode.gcm.aad_cache, cache_len);
  36. memcpy(&tbuf[cache_len], data, data_offset);
  37. xor_buf(tbuf, out_buf, AES_BLOCK_SIZE);
  38. aes_gf2_mul(out_buf, out_buf, ctx->mode.gcm.ghash_key);
  39. ctx->mode.gcm.aad_cache_len = 0;
  40. }
  41. }
  42.  
  43. // now process any remaining aad data
  44. for(uint24_t idx = data_offset; idx < len; idx += AES_BLOCK_SIZE){
  45. size_t bytes_copy = MIN(AES_BLOCK_SIZE, len - idx);
  46. if(bytes_copy < AES_BLOCK_SIZE){
  47. // if aad_len < block size, write bytes to queue.
  48. // no return here because this condition should just exit out next loop
  49. memcpy(ctx->mode.gcm.aad_cache, &data[idx], bytes_copy);
  50. ctx->mode.gcm.aad_cache_len = bytes_copy;
  51. }
  52. else {
  53. // if aad_len >= block size, update hash for block
  54. memcpy(tbuf, &data[idx], AES_BLOCK_SIZE);
  55. xor_buf(tbuf, out_buf, AES_BLOCK_SIZE);
  56. aes_gf2_mul(out_buf, out_buf, ctx->mode.gcm.ghash_key);
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement