1 /* 2 * AES-128 CTR 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.h" 20 #include "aes_wrap.h" 21 22 /** 23 * aes_128_ctr_encrypt - AES-128 CTR mode encryption 24 * @key: Key for encryption (16 bytes) 25 * @nonce: Nonce for counter mode (16 bytes) 26 * @data: Data to encrypt in-place 27 * @data_len: Length of data in bytes 28 * Returns: 0 on success, -1 on failure 29 */ 30 int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce, 31 u8 *data, size_t data_len) 32 { 33 void *ctx; 34 size_t j, len, left = data_len; 35 int i; 36 u8 *pos = data; 37 u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE]; 38 39 ctx = aes_encrypt_init(key, 16); 40 if (ctx == NULL) 41 return -1; 42 os_memcpy(counter, nonce, AES_BLOCK_SIZE); 43 44 while (left > 0) { 45 aes_encrypt(ctx, counter, buf); 46 47 len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE; 48 for (j = 0; j < len; j++) 49 pos[j] ^= buf[j]; 50 pos += len; 51 left -= len; 52 53 for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) { 54 counter[i]++; 55 if (counter[i]) 56 break; 57 } 58 } 59 aes_encrypt_deinit(ctx); 60 return 0; 61 } 62