I have the following code working for AES-256 ECB encryption using a simple byte-oriented AES-256 library I found here.
Main:
#define DUMP(s, i, buf, sz) {printf(s); \
for (i = 0; i < (sz);i++) \
printf("%02x ", buf[i]); \
printf("\n");}
int main (int argc, char *argv[])
{
aes256_context ctx;
uint8_t key[32] = "39P8TXDMBCYF4C1NI1CDFJ1WL6P5TTKZ";
uint8_t buf[16] = "KUC7EWG6M2D1WW8F";
uint8_t i;
DUMP("txt: ", i, buf, sizeof(buf));
DUMP("key: ", i, key, sizeof(key));
printf("---\n");
aes256_init(&ctx, key);
aes256_encrypt_ecb(&ctx, buf);
DUMP("enc: ", i, buf, sizeof(buf));
aes256_init(&ctx, key);
aes256_decrypt_ecb(&ctx, buf);
DUMP("dec: ", i, buf, sizeof(buf));
aes256_done(&ctx);
return 0;
}
Encryption function:
void aes256_encrypt_ecb(aes256_context *ctx, uint8_t *buf)
{
uint8_t i, rcon;
aes_addRoundKey_cpy(buf, ctx->enckey, ctx->key);
for(i = 1, rcon = 1; i < 14; ++i)
{
aes_subBytes(buf);
aes_shiftRows(buf);
aes_mixColumns(buf);
if( i & 1 ) aes_addRoundKey( buf, &ctx->key[16]);
else aes_expandEncKey(ctx->key, &rcon), aes_addRoundKey(buf, ctx->key);
}
aes_subBytes(buf);
aes_shiftRows(buf);
aes_expandEncKey(ctx->key, &rcon);
aes_addRoundKey(buf, ctx->key);
} /* aes256_encrypt */
I want to add an IV to this program to create AES-256 CBC mode. From what I understand, IV implementation is as follows:
- XOR the first block with the IV.
- XOR all following blocks with the cipher text of the previous block.
My question is what does the logic look like? How do I implement that into my code?