Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // internal supporting struct for gcm
- typedef struct _aes_gcm {
- uint8_t last_block_stop;
- uint8_t last_block[16];
- uint8_t ghash_key[16];
- uint8_t aad_cache[16];
- uint8_t aad_cache_len;
- size_t aad_len;
- uint8_t auth_tag[16];
- uint8_t auth_digest[16];
- } aes_gcm_t;
- #define ghash_start(buf) memset((buf), 0, 16)
- void ghash(aes_ctx *ctx, uint8_t *out_buf, const uint8_t *data, size_t len)
- {
- uint8_t tbuf[AES_BLOCK_SIZE];
- size_t data_offset = 0;
- // the cache allows for incomplete blocks to be queued
- // the next call to update will concat the queue and new aad
- if(ctx->mode.gcm.aad_cache_len){
- size_t cache_len = ctx->mode.gcm.aad_cache_len;
- data_offset = MIN(len, AES_BLOCK_SIZE - cache_len);
- if(data_offset + cache_len < AES_BLOCK_SIZE){
- // if new aad is not enough to fill a block, update queue and stop w/o processing
- memcpy(&ctx->mode.gcm.aad_cache[cache_len], data, data_offset);
- ctx->mode.gcm.aad_cache_len += data_offset;
- return;
- }
- else {
- // if new aad is enough to fill a block, concat queue and rest of block from aad
- // then update hash
- memcpy(tbuf, ctx->mode.gcm.aad_cache, cache_len);
- memcpy(&tbuf[cache_len], data, data_offset);
- xor_buf(tbuf, out_buf, AES_BLOCK_SIZE);
- aes_gf2_mul(out_buf, out_buf, ctx->mode.gcm.ghash_key);
- ctx->mode.gcm.aad_cache_len = 0;
- }
- }
- // now process any remaining aad data
- for(uint24_t idx = data_offset; idx < len; idx += AES_BLOCK_SIZE){
- size_t bytes_copy = MIN(AES_BLOCK_SIZE, len - idx);
- if(bytes_copy < AES_BLOCK_SIZE){
- // if aad_len < block size, write bytes to queue.
- // no return here because this condition should just exit out next loop
- memcpy(ctx->mode.gcm.aad_cache, &data[idx], bytes_copy);
- ctx->mode.gcm.aad_cache_len = bytes_copy;
- }
- else {
- // if aad_len >= block size, update hash for block
- memcpy(tbuf, &data[idx], AES_BLOCK_SIZE);
- xor_buf(tbuf, out_buf, AES_BLOCK_SIZE);
- aes_gf2_mul(out_buf, out_buf, ctx->mode.gcm.ghash_key);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement