basic/aes_ctr/aes_ctr.c

See examples/basic/aes-ctr

/*
* ZentriOS SDK LICENSE AGREEMENT | Zentri.com, 2015.
*
* Use of source code and/or libraries contained in the ZentriOS SDK is
* subject to the Zentri Operating System SDK license agreement and
* applicable open source license agreements.
*
*/
/* Documentation for this app is available online.
* See https://docs.zentri.com/wifi/sdk/latest/examples/basic/aes-ctr
*/
#include "zos.h"
#define AES_BLOCK_SIZE 16
#define AES_BIT_SIZE (AES_BLOCK_SIZE * 8)
typedef struct
{
union
{
uint8_t buf[AES_BLOCK_SIZE];
struct
{
uint8_t nonce[AES_BLOCK_SIZE - sizeof(uint32_t)];
uint32_t counter;
} iv;
} iv;
} aes_info_t;
static uint8_t* encrypt_block(aes_info_t *aes, uint8_t *ptr);
/*************************************************************************************************/
void zn_app_init(void)
{
aes_info_t encrypt;
aes_info_t decrypt;
uint8_t key[AES_BLOCK_SIZE];
uint8_t test_data[AES_BLOCK_SIZE+1];
ZOS_LOG("AES CTR Example");
memset(encrypt.iv.buf, 0xAA, sizeof(encrypt.iv.buf));
memset(decrypt.iv.buf, 0xAA, sizeof(encrypt.iv.buf));
strcpy((char*)test_data, "**Client Hello**");
for(int i = 0; i < AES_BLOCK_SIZE; ++i)
{
key[i] = i;
}
aes_setkey_enc(&encrypt.ctx, key, AES_BIT_SIZE);
aes_setkey_enc(&decrypt.ctx, key, AES_BIT_SIZE);
ZOS_LOG("Unencrypted data: %s", (char*)test_data);
encrypt_block(&encrypt, test_data);
zn_dump_buffer(test_data, AES_BLOCK_SIZE, "Encrypted Buffer", ZOS_DUMP_FLAGS(16, 1, LITTLE, ADD_SPACE, NO_ADDRESSES, NO_ASCII ));
encrypt_block(&decrypt, test_data);
zn_dump_buffer(test_data, AES_BLOCK_SIZE, "Decrypted Buffer", ZOS_DUMP_FLAGS(16, 1, LITTLE, ADD_SPACE, NO_ADDRESSES, PRINT_ASCII ));
}
/*************************************************************************************************/
zos_bool_t zn_app_idle(void)
{
return ZOS_FALSE;
}
/*************************************************************************************************/
static uint8_t* encrypt_block(aes_info_t *aes, uint8_t *ptr)
{
uint8_t ctr_key[AES_BLOCK_SIZE];
uint8_t *ctr_key_ptr = ctr_key;
// Set up next CTR key.
memcpy(ctr_key, aes->iv.buf, AES_BLOCK_SIZE);
aes_encrypt_ecb(&aes->ctx, ctr_key, ctr_key);
aes->iv.iv.counter = __REV(__REV(aes->iv.iv.counter) + 1);
// Decrypt CTR block.
for (int i = AES_BLOCK_SIZE; i > 0; --i)
{
*ptr++ ^= *ctr_key_ptr++;
}
return ptr;
}