Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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);
- }
- }
- }
- void aes_gcm_prepare_iv(aes_ctx *ctx, const uint8_t *iv, size_t iv_len)
- {
- uint8_t tbuf[AES_BLOCK_SIZE];
- // memset(ctx->iv, 0, AES_BLOCK_SIZE);
- // ^^ this should already be zero'd from aes_init
- if (iv_len == 12) {
- /* Prepare block J_0 = IV || 0^31 || 1 [len(IV) = 96] */
- // memcpy(ctx->iv, iv, iv_len);
- // ^^ this should already be done by aes_init
- ctx->iv[AES_BLOCK_SIZE - 1] = 0x01;
- } else {
- /*
- * s = 128 * ceil(len(IV)/128) - len(IV)
- * J_0 = GHASH_H(IV || 0^(s+64) || [len(IV)]_64)
- */
- // hash the IV. Pad to block size
- memset(tbuf, 0, AES_BLOCK_SIZE);
- memcpy(tbuf, iv, iv_len);
- ghash(ctx, ctx->iv, tbuf, sizeof(tbuf));
- memset(tbuf, 0, AES_BLOCK_SIZE>>1);
- bytelen_to_bitlen(iv_len, &tbuf[8]); // outputs in BE
- ghash(ctx, ctx->iv, tbuf, sizeof(tbuf));
- memrev(ctx->iv, AES_BLOCK_SIZE);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement