2009-08-13 10:40:28 +02:00
|
|
|
/*
|
2016-10-10 18:27:57 +02:00
|
|
|
* AES-128/192/256 CTR
|
2009-08-13 10:40:28 +02:00
|
|
|
*
|
|
|
|
* Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
|
|
|
|
*
|
2012-02-11 15:46:35 +01:00
|
|
|
* This software may be distributed under the terms of the BSD license.
|
|
|
|
* See README for more details.
|
2009-08-13 10:40:28 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include "includes.h"
|
|
|
|
|
|
|
|
#include "common.h"
|
2009-08-17 19:27:25 +02:00
|
|
|
#include "aes.h"
|
2009-11-24 23:57:00 +01:00
|
|
|
#include "aes_wrap.h"
|
2009-08-13 10:40:28 +02:00
|
|
|
|
|
|
|
/**
|
2016-10-10 18:27:57 +02:00
|
|
|
* aes_ctr_encrypt - AES-128/192/256 CTR mode encryption
|
|
|
|
* @key: Key for encryption (key_len bytes)
|
|
|
|
* @key_len: Length of the key (16, 24, or 32 bytes)
|
2009-08-13 10:40:28 +02:00
|
|
|
* @nonce: Nonce for counter mode (16 bytes)
|
|
|
|
* @data: Data to encrypt in-place
|
|
|
|
* @data_len: Length of data in bytes
|
|
|
|
* Returns: 0 on success, -1 on failure
|
|
|
|
*/
|
2016-10-10 18:27:57 +02:00
|
|
|
int aes_ctr_encrypt(const u8 *key, size_t key_len, const u8 *nonce,
|
|
|
|
u8 *data, size_t data_len)
|
2009-08-13 10:40:28 +02:00
|
|
|
{
|
|
|
|
void *ctx;
|
|
|
|
size_t j, len, left = data_len;
|
|
|
|
int i;
|
|
|
|
u8 *pos = data;
|
2009-08-17 19:27:25 +02:00
|
|
|
u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE];
|
2009-08-13 10:40:28 +02:00
|
|
|
|
2016-10-10 18:27:57 +02:00
|
|
|
ctx = aes_encrypt_init(key, key_len);
|
2009-08-13 10:40:28 +02:00
|
|
|
if (ctx == NULL)
|
|
|
|
return -1;
|
2009-08-17 19:27:25 +02:00
|
|
|
os_memcpy(counter, nonce, AES_BLOCK_SIZE);
|
2009-08-13 10:40:28 +02:00
|
|
|
|
|
|
|
while (left > 0) {
|
|
|
|
aes_encrypt(ctx, counter, buf);
|
|
|
|
|
2009-08-17 19:27:25 +02:00
|
|
|
len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE;
|
2009-08-13 10:40:28 +02:00
|
|
|
for (j = 0; j < len; j++)
|
|
|
|
pos[j] ^= buf[j];
|
|
|
|
pos += len;
|
|
|
|
left -= len;
|
|
|
|
|
2009-08-17 19:27:25 +02:00
|
|
|
for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) {
|
2009-08-13 10:40:28 +02:00
|
|
|
counter[i]++;
|
|
|
|
if (counter[i])
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
aes_encrypt_deinit(ctx);
|
|
|
|
return 0;
|
|
|
|
}
|
2016-10-10 18:27:57 +02:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* aes_128_ctr_encrypt - AES-128 CTR mode encryption
|
|
|
|
* @key: Key for encryption (key_len bytes)
|
|
|
|
* @nonce: Nonce for counter mode (16 bytes)
|
|
|
|
* @data: Data to encrypt in-place
|
|
|
|
* @data_len: Length of data in bytes
|
|
|
|
* Returns: 0 on success, -1 on failure
|
|
|
|
*/
|
|
|
|
int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce,
|
|
|
|
u8 *data, size_t data_len)
|
|
|
|
{
|
|
|
|
return aes_ctr_encrypt(key, 16, nonce, data, data_len);
|
|
|
|
}
|