security/aes_ctr/main.c

/*******************************************************************************
* # License
* Copyright 2019 Silicon Laboratories Inc. www.silabs.com
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
/* Documentation for this app is available online.
* See https://docs.silabs.com/gecko-os/4/standard/latest/sdk/examples/security/aes-ctr
*/
#include "gos.h"
#define APPLICATION_START_LINE "\r\nAES CTR example starting ..."
typedef struct
{
} aes_context_t;
static uint8_t* encrypt_block(aes_context_t *aes, uint8_t *ptr);
/*************************************************************************************************/
void gos_app_init(void)
{
aes_context_t encrypt;
aes_context_t decrypt;
uint8_t key[AES128_BLOCK_SIZE];
uint8_t test_data[AES128_BLOCK_SIZE+1];
GOS_LOG(APPLICATION_START_LINE);
memset(encrypt.iv.buf, 0xAA, AES128_BLOCK_SIZE);
memset(decrypt.iv.buf, 0xAA, AES128_BLOCK_SIZE);
strcpy((char*)test_data, "**Client Hello**");
for (int i = 0; i < AES128_BLOCK_SIZE; ++i)
{
key[i] = i;
}
gos_aes_setkey_enc(&encrypt.ctx, key, AES128_BLOCK_BITS);
gos_aes_setkey_enc(&decrypt.ctx, key, AES128_BLOCK_BITS);
GOS_LOG("Unencrypted data: %s", (char*)test_data);
encrypt_block(&encrypt, test_data);
gos_dump_buffer(test_data, AES128_BLOCK_SIZE, "Encrypted Buffer",
GOS_DUMP_FLAGS(16, 1, LITTLE, ADD_SPACE, NO_ADDRESSES, NO_ASCII ));
encrypt_block(&decrypt, test_data);
gos_dump_buffer(test_data, AES128_BLOCK_SIZE, "Decrypted Buffer",
GOS_DUMP_FLAGS(16, 1, LITTLE, ADD_SPACE, NO_ADDRESSES, PRINT_ASCII ));
}
/*************************************************************************************************/
static uint8_t* encrypt_block(aes_context_t *aes, uint8_t *ptr)
{
uint8_t ctr_key[AES128_BLOCK_SIZE];
uint8_t *ctr_key_ptr = ctr_key;
// Set up next CTR key
memcpy(ctr_key, aes->iv.buf, AES128_BLOCK_SIZE);
gos_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 = AES128_BLOCK_SIZE; i > 0; --i)
{
*ptr++ ^= *ctr_key_ptr++;
}
return ptr;
}