1
0
Fork 0
nrf51-cryptolib/block.c

101 lines
2.1 KiB
C
Raw Normal View History

2016-06-01 15:07:50 -04:00
/* Utility functions for manipulating block_t structures; 128bit
blocks of data for AES & CMAC */
#include "block.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
2016-06-01 15:07:50 -04:00
2016-06-01 15:25:05 -04:00
#ifdef HOST_BUILD
2016-06-01 15:07:50 -04:00
void block_print(char const * const label,
uint8_t const * const b) {
2016-06-01 15:07:50 -04:00
if (label != NULL) {
2016-06-07 12:42:08 -04:00
printf("%s: ", label);
2016-06-01 15:07:50 -04:00
} else {
printf("\n");
}
for(int i = 0; i < 16; i++) {
printf("%.2x", b[i]);
2016-06-01 15:07:50 -04:00
if (!((i+1) % 4)) {
printf(" ");
}
}
printf("\n");
return;
}
2016-06-07 12:42:08 -04:00
void block_print_bytes(char const * const label,
uint8_t const * const b, uint32_t num_bytes) {
printf("%s: ", label);
for(int i = 0; i < num_bytes; i++) {
printf("%.2x", b[i]);
if (!((i+1) % 4)) {
printf(" ");
}
}
printf("\n");
}
2016-06-01 15:25:05 -04:00
#endif /* HOST_BUILD */
void block_xor(uint8_t *dest, uint8_t * const a, uint8_t * const b) {
2016-06-01 15:07:50 -04:00
for (uint_fast8_t i = 0; i < 4; i++) {
*((uint32_t *)dest+i) = *((uint32_t *)a+i) ^ *((uint32_t *)b+i);
2016-06-01 15:07:50 -04:00
}
return;
2016-06-01 15:07:50 -04:00
}
void block_shiftr(uint8_t *dest, uint8_t * const a, uint_fast8_t num) {
2016-06-01 15:07:50 -04:00
uint_fast8_t n = (num <= 8 ? num : 8);
for (int_fast8_t i = 15; i >= 0; i--) {
/* Shift right from LSB to MSB */
dest[i] = a[i] >> n;
2016-06-01 15:07:50 -04:00
if (i != 0) {
dest[i] |= (a[i-1] << (8 - n));
2016-06-01 15:07:50 -04:00
}
}
if (num - n != 0) {
block_shiftr(dest, dest, num - n);
}
return;
2016-06-01 15:07:50 -04:00
}
void block_shiftl(uint8_t *dest, uint8_t * const a, uint_fast8_t num) {
2016-06-01 15:07:50 -04:00
uint_fast8_t n = (num <= 8 ? num : 8);
for (int_fast8_t i = 0; i < 16; i++) {
dest[i] = a[i] << n;
2016-06-01 15:07:50 -04:00
if (i != 15) {
dest[i] |= (a[i+1] >> (8 - n));
2016-06-01 15:07:50 -04:00
}
}
if (num - n != 0) {
block_shiftl(dest, dest, num - n);
}
return;
2016-06-01 15:07:50 -04:00
}
void block_incr(uint8_t *in) {
for (int_fast8_t i = 15; i > 0 ; i--) {
uint8_t prev = in[i];
in[i] += 1;
if (in[i] > prev) {
/* No overflow, changes propagate no further */
break;
}
}
return;
}
void block_decr(uint8_t *in) {
for (int_fast8_t i = 15; i > 0 ; i--) {
uint8_t prev = in[i];
in[i] -= 1;
if (in[i] < prev) {
/* No overflow, changes propagate no further */
break;
}
}
return;
}