1
0
Fork 0
nrf51-cryptolib/ctr.c

37 lines
886 B
C
Raw Normal View History

#include <string.h>
#include "aes.h"
#include "block.h"
static uint8_t g_counter[16];
void aes128_ctr_init(uint8_t *key, uint8_t *counter) {
2016-06-07 12:51:42 -04:00
if (counter != NULL) {
memcpy(g_counter, counter, 16);
}
if (key != NULL) {
2016-09-29 12:50:08 -04:00
aes128_init(key);
}
}
2016-06-07 12:42:08 -04:00
void aes128_ctr_evolve_counter(void) {
2016-06-07 12:51:42 -04:00
block_incr(g_counter);
return;
}
void aes128_ctr(uint8_t *dest, uint8_t *msg, uint32_t msg_len) {
2017-08-02 15:59:58 -04:00
uint8_t *buffer;
2016-06-07 12:51:42 -04:00
uint32_t num_blocks = msg_len / 16;
for (uint32_t i = 0; i < num_blocks; i++) {
2017-08-02 15:59:58 -04:00
buffer = aes128_ecb(g_counter);
2016-06-07 12:51:42 -04:00
aes128_ctr_evolve_counter();
block_xor(dest + (i * 16), msg + (i * 16), buffer);
}
if (msg_len % 16) {
2017-08-02 15:59:58 -04:00
buffer = aes128_ecb(g_counter);
2016-06-07 12:51:42 -04:00
for (uint8_t i = 0; i < msg_len % 16; i++) {
dest[num_blocks * 16 + i] = msg[num_blocks * 16 + i] ^ buffer[i];
}
2016-06-07 12:42:08 -04:00
}
}