#include <sys/types.h>
#include <sys/systm.h>
#include <sys/param.h>
#include <sys/endian.h>
#include <opencrypto/cbc_mac.h>
#include <opencrypto/xform_auth.h>
static void
xor_and_encrypt(struct aes_cbc_mac_ctx *ctx,
const uint8_t *src, uint8_t *dst)
{
#define NWORDS (CCM_CBC_BLOCK_LEN / sizeof(uint64_t))
uint64_t b1[NWORDS], b2[NWORDS], temp[NWORDS];
memcpy(b1, src, CCM_CBC_BLOCK_LEN);
memcpy(b2, dst, CCM_CBC_BLOCK_LEN);
for (size_t count = 0; count < NWORDS; count++)
temp[count] = b1[count] ^ b2[count];
rijndaelEncrypt(ctx->keysched, ctx->rounds, (void *)temp, dst);
#undef NWORDS
}
void
AES_CBC_MAC_Init(void *vctx)
{
struct aes_cbc_mac_ctx *ctx;
ctx = vctx;
bzero(ctx, sizeof(*ctx));
}
void
AES_CBC_MAC_Setkey(void *vctx, const uint8_t *key, u_int klen)
{
struct aes_cbc_mac_ctx *ctx;
ctx = vctx;
ctx->rounds = rijndaelKeySetupEnc(ctx->keysched, key, klen * 8);
}
void
AES_CBC_MAC_Reinit(void *vctx, const uint8_t *nonce, u_int nonceLen)
{
struct aes_cbc_mac_ctx *ctx = vctx;
ctx->nonce = nonce;
ctx->nonceLength = nonceLen;
ctx->blockIndex = 0;
memset(ctx->block, 0, CCM_CBC_BLOCK_LEN);
}
int
AES_CBC_MAC_Update(void *vctx, const void *vdata, u_int length)
{
struct aes_cbc_mac_ctx *ctx;
const uint8_t *data;
size_t copy_amt;
ctx = vctx;
data = vdata;
while (length != 0) {
uint8_t *ptr;
if (ctx->blockIndex == 0 && length >= CCM_CBC_BLOCK_LEN) {
xor_and_encrypt(ctx, data, ctx->block);
length -= CCM_CBC_BLOCK_LEN;
data += CCM_CBC_BLOCK_LEN;
continue;
}
copy_amt = MIN(sizeof(ctx->staging_block) - ctx->blockIndex,
length);
ptr = ctx->staging_block + ctx->blockIndex;
bcopy(data, ptr, copy_amt);
data += copy_amt;
ctx->blockIndex += copy_amt;
length -= copy_amt;
if (ctx->blockIndex == sizeof(ctx->staging_block)) {
xor_and_encrypt(ctx, ctx->staging_block, ctx->block);
ctx->blockIndex = 0;
}
}
return (0);
}
void
AES_CBC_MAC_Final(uint8_t *buf, void *vctx)
{
struct aes_cbc_mac_ctx *ctx;
uint8_t s0[CCM_CBC_BLOCK_LEN];
ctx = vctx;
if (ctx->blockIndex != 0) {
memset(ctx->staging_block + ctx->blockIndex, 0,
CCM_CBC_BLOCK_LEN - ctx->blockIndex);
xor_and_encrypt(ctx, ctx->staging_block, ctx->block);
}
explicit_bzero(ctx->staging_block, sizeof(ctx->staging_block));
bzero(s0, sizeof(s0));
s0[0] = (15 - ctx->nonceLength) - 1;
bcopy(ctx->nonce, s0 + 1, ctx->nonceLength);
rijndaelEncrypt(ctx->keysched, ctx->rounds, s0, s0);
for (size_t indx = 0; indx < AES_CBC_MAC_HASH_LEN; indx++)
buf[indx] = ctx->block[indx] ^ s0[indx];
explicit_bzero(s0, sizeof(s0));
}