#include "common.h" static const char base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const uint8_t base64_index[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; void ecdaa_rand(void *buffer, size_t buflen) { getrandom(buffer, buflen, 0); } char bin2hex(uint8_t byte) { uint8_t word = byte & 0x0f; char hex = 0; if (word >= 0 && word <= 9) hex = word + '0'; else if (word >= 10 && word <= 15) hex = word - 10 + 'A'; return hex; } uint8_t hex2bin(char hex) { uint8_t byte = 0; if (hex >= '0' && hex <= '9') byte = hex - '0'; else if (hex >= 'a' && hex <= 'f') byte = hex - 'a' + 10; else if (hex >= 'A' && hex <= 'F') byte = hex - 'A' + 10; return byte; } void ecdaa_hextobin(const char *in_hex, uint8_t *out_bin, size_t outlen) { for (size_t i = 0, j = 0; i < outlen; i++, j+=2) { uint8_t val = hex2bin(in_hex[j]); val += hex2bin(in_hex[j+1]) * 16; out_bin[i] = (char) val; } } void ecdaa_bintohex(const uint8_t *in_bin, char *out_hex, size_t inlen) { for (size_t i = 0, j = 0; i < inlen; i++, j+=2) { out_hex[j] = bin2hex(in_bin[i]); out_hex[j+1] = bin2hex(in_bin[i] >> 4); } } void ecdaa_encode(const uint8_t *in_dec, char *out_enc, size_t inlen) { int outlen = 4 * ((inlen + 2) / 3); int i = 0; int j = 0; while(i < inlen) { uint32_t octet_a = i < inlen ? in_dec[i++] : 0; uint32_t octet_b = i < inlen ? in_dec[i++] : 0; uint32_t octet_c = i < inlen ? in_dec[i++] : 0; uint32_t triple = (octet_a << 16) + (octet_b << 8) + octet_c; out_enc[j++] = base64_table[(triple >> 18) & 0x3F]; out_enc[j++] = base64_table[(triple >> 12) & 0x3F]; out_enc[j++] = base64_table[(triple >> 6) & 0x3F]; out_enc[j++] = base64_table[(triple) & 0x3F]; } switch (inlen % 3) { case 1: out_enc[j-2] = '='; case 2: out_enc[j-1] = '='; default: break; } } void ecdaa_decode(const uint8_t *in_enc, char *out_dec, size_t outlen) { int inlen = 4 * ((outlen + 2) / 3); int i = 0; int j = 0; while (i < inlen) { uint32_t sextet_a = in_enc[i] == '=' ? 0 & i++ : base64_index[in_enc[i++]]; uint32_t sextet_b = in_enc[i] == '=' ? 0 & i++ : base64_index[in_enc[i++]]; uint32_t sextet_c = in_enc[i] == '=' ? 0 & i++ : base64_index[in_enc[i++]]; uint32_t sextet_d = in_enc[i] == '=' ? 0 & i++ : base64_index[in_enc[i++]]; uint32_t triple = (sextet_a << 18) + (sextet_b << 12) + (sextet_c << 6) + sextet_d; if (j < outlen) out_dec[j++] = (triple >> 16) & 0xFF; if (j < outlen) out_dec[j++] = (triple >> 8) & 0xFF; if (j < outlen) out_dec[j++] = triple & 0xFF; } }