Crypto build cleanup: remove CONFIG_NO_AES_*
[mech_eap.git] / src / crypto / aes-cbc.c
1 /*
2  * AES-128 CBC
3  *
4  * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * Alternatively, this software may be distributed under the terms of BSD
11  * license.
12  *
13  * See README and COPYING for more details.
14  */
15
16 #include "includes.h"
17
18 #include "common.h"
19 #include "aes_i.h"
20
21 /**
22  * aes_128_cbc_encrypt - AES-128 CBC encryption
23  * @key: Encryption key
24  * @iv: Encryption IV for CBC mode (16 bytes)
25  * @data: Data to encrypt in-place
26  * @data_len: Length of data in bytes (must be divisible by 16)
27  * Returns: 0 on success, -1 on failure
28  */
29 int aes_128_cbc_encrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
30 {
31         void *ctx;
32         u8 cbc[BLOCK_SIZE];
33         u8 *pos = data;
34         int i, j, blocks;
35
36         ctx = aes_encrypt_init(key, 16);
37         if (ctx == NULL)
38                 return -1;
39         os_memcpy(cbc, iv, BLOCK_SIZE);
40
41         blocks = data_len / BLOCK_SIZE;
42         for (i = 0; i < blocks; i++) {
43                 for (j = 0; j < BLOCK_SIZE; j++)
44                         cbc[j] ^= pos[j];
45                 aes_encrypt(ctx, cbc, cbc);
46                 os_memcpy(pos, cbc, BLOCK_SIZE);
47                 pos += BLOCK_SIZE;
48         }
49         aes_encrypt_deinit(ctx);
50         return 0;
51 }
52
53
54 /**
55  * aes_128_cbc_decrypt - AES-128 CBC decryption
56  * @key: Decryption key
57  * @iv: Decryption IV for CBC mode (16 bytes)
58  * @data: Data to decrypt in-place
59  * @data_len: Length of data in bytes (must be divisible by 16)
60  * Returns: 0 on success, -1 on failure
61  */
62 int aes_128_cbc_decrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
63 {
64         void *ctx;
65         u8 cbc[BLOCK_SIZE], tmp[BLOCK_SIZE];
66         u8 *pos = data;
67         int i, j, blocks;
68
69         ctx = aes_decrypt_init(key, 16);
70         if (ctx == NULL)
71                 return -1;
72         os_memcpy(cbc, iv, BLOCK_SIZE);
73
74         blocks = data_len / BLOCK_SIZE;
75         for (i = 0; i < blocks; i++) {
76                 os_memcpy(tmp, pos, BLOCK_SIZE);
77                 aes_decrypt(ctx, pos, pos);
78                 for (j = 0; j < BLOCK_SIZE; j++)
79                         pos[j] ^= cbc[j];
80                 os_memcpy(cbc, tmp, BLOCK_SIZE);
81                 pos += BLOCK_SIZE;
82         }
83         aes_decrypt_deinit(ctx);
84         return 0;
85 }