aes-cbc.c
Go to the documentation of this file.00001
00017 #include "includes.h"
00018
00019 #include "common.h"
00020 #include "aes.h"
00021
00031 int aes_128_cbc_encrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
00032 {
00033 void *ctx;
00034 u8 cbc[AES_BLOCK_SIZE];
00035 u8 *pos = data;
00036 int i, j, blocks;
00037
00038 ctx = aes_encrypt_init(key, 16);
00039 if (ctx == NULL)
00040 return -1;
00041 os_memcpy(cbc, iv, AES_BLOCK_SIZE);
00042
00043 blocks = data_len / AES_BLOCK_SIZE;
00044 for (i = 0; i < blocks; i++) {
00045 for (j = 0; j < AES_BLOCK_SIZE; j++)
00046 cbc[j] ^= pos[j];
00047 aes_encrypt(ctx, cbc, cbc);
00048 os_memcpy(pos, cbc, AES_BLOCK_SIZE);
00049 pos += AES_BLOCK_SIZE;
00050 }
00051 aes_encrypt_deinit(ctx);
00052 return 0;
00053 }
00054
00055
00065 int aes_128_cbc_decrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
00066 {
00067 void *ctx;
00068 u8 cbc[AES_BLOCK_SIZE], tmp[AES_BLOCK_SIZE];
00069 u8 *pos = data;
00070 int i, j, blocks;
00071
00072 ctx = aes_decrypt_init(key, 16);
00073 if (ctx == NULL)
00074 return -1;
00075 os_memcpy(cbc, iv, AES_BLOCK_SIZE);
00076
00077 blocks = data_len / AES_BLOCK_SIZE;
00078 for (i = 0; i < blocks; i++) {
00079 os_memcpy(tmp, pos, AES_BLOCK_SIZE);
00080 aes_decrypt(ctx, pos, pos);
00081 for (j = 0; j < AES_BLOCK_SIZE; j++)
00082 pos[j] ^= cbc[j];
00083 os_memcpy(cbc, tmp, AES_BLOCK_SIZE);
00084 pos += AES_BLOCK_SIZE;
00085 }
00086 aes_decrypt_deinit(ctx);
00087 return 0;
00088 }
00089