1 /*
2 * AES-128/192/256 CTR
3 *
4 * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
5 *
6 * This software may be distributed under the terms of the BSD license.
7 * See README for more details.
8 */
9
10 #include "includes.h"
11
12 #include "common.h"
13 #include "aes.h"
14 #include "aes_wrap.h"
15
16 /**
17 * aes_ctr_encrypt - AES-128/192/256 CTR mode encryption
18 * @key: Key for encryption (key_len bytes)
19 * @key_len: Length of the key (16, 24, or 32 bytes)
20 * @nonce: Nonce for counter mode (16 bytes)
21 * @data: Data to encrypt in-place
22 * @data_len: Length of data in bytes
23 * Returns: 0 on success, -1 on failure
24 */
aes_ctr_encrypt(const u8 * key,size_t key_len,const u8 * nonce,u8 * data,size_t data_len)25 int aes_ctr_encrypt(const u8 *key, size_t key_len, const u8 *nonce,
26 u8 *data, size_t data_len)
27 {
28 void *ctx;
29 size_t j, len, left = data_len;
30 int i;
31 u8 *pos = data;
32 u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE];
33
34 ctx = aes_encrypt_init(key, key_len);
35 if (ctx == NULL)
36 return -1;
37 os_memcpy(counter, nonce, AES_BLOCK_SIZE);
38
39 while (left > 0) {
40 aes_encrypt(ctx, counter, buf);
41
42 len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE;
43 for (j = 0; j < len; j++)
44 pos[j] ^= buf[j];
45 pos += len;
46 left -= len;
47
48 for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) {
49 counter[i]++;
50 if (counter[i])
51 break;
52 }
53 }
54 aes_encrypt_deinit(ctx);
55 return 0;
56 }
57
58
59 /**
60 * aes_128_ctr_encrypt - AES-128 CTR mode encryption
61 * @key: Key for encryption (key_len bytes)
62 * @nonce: Nonce for counter mode (16 bytes)
63 * @data: Data to encrypt in-place
64 * @data_len: Length of data in bytes
65 * Returns: 0 on success, -1 on failure
66 */
aes_128_ctr_encrypt(const u8 * key,const u8 * nonce,u8 * data,size_t data_len)67 int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce,
68 u8 *data, size_t data_len)
69 {
70 return aes_ctr_encrypt(key, 16, nonce, data, data_len);
71 }
72