/src/hostap/src/crypto/aes-ctr.c
Line | Count | Source (jump to first uncovered line) |
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 | | */ |
25 | | int aes_ctr_encrypt(const u8 *key, size_t key_len, const u8 *nonce, |
26 | | u8 *data, size_t data_len) |
27 | 0 | { |
28 | 0 | void *ctx; |
29 | 0 | size_t j, len, left = data_len; |
30 | 0 | int i; |
31 | 0 | u8 *pos = data; |
32 | 0 | u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE]; |
33 | |
|
34 | 0 | ctx = aes_encrypt_init(key, key_len); |
35 | 0 | if (ctx == NULL) |
36 | 0 | return -1; |
37 | 0 | os_memcpy(counter, nonce, AES_BLOCK_SIZE); |
38 | |
|
39 | 0 | while (left > 0) { |
40 | 0 | aes_encrypt(ctx, counter, buf); |
41 | |
|
42 | 0 | len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE; |
43 | 0 | for (j = 0; j < len; j++) |
44 | 0 | pos[j] ^= buf[j]; |
45 | 0 | pos += len; |
46 | 0 | left -= len; |
47 | |
|
48 | 0 | for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) { |
49 | 0 | counter[i]++; |
50 | 0 | if (counter[i]) |
51 | 0 | break; |
52 | 0 | } |
53 | 0 | } |
54 | 0 | aes_encrypt_deinit(ctx); |
55 | 0 | return 0; |
56 | 0 | } |
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 | | */ |
67 | | int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce, |
68 | | u8 *data, size_t data_len) |
69 | 0 | { |
70 | 0 | return aes_ctr_encrypt(key, 16, nonce, data, data_len); |
71 | 0 | } |