|
| 1 | +#include <mbedtls/aes.h> |
| 2 | +#include "pico/stdlib.h" |
| 3 | + |
| 4 | +extern void lock_key(); |
| 5 | + |
| 6 | +int mb_aes_crypt_ctr_xor(mbedtls_aes_context *ctx, |
| 7 | + size_t length, |
| 8 | + unsigned char iv0[16], |
| 9 | + unsigned char nonce_xor[16], |
| 10 | + unsigned char stream_block[16], |
| 11 | + const unsigned char *input, |
| 12 | + unsigned char *output) |
| 13 | +{ |
| 14 | + int c; |
| 15 | + int ret = 0; |
| 16 | + size_t n = 0; |
| 17 | + uint32_t counter = 0; |
| 18 | + |
| 19 | + assert(length == (uint32_t)length); |
| 20 | + |
| 21 | + while (length--) { |
| 22 | + if (n == 0) { |
| 23 | + for (int i = 16; i > 0; i--) { |
| 24 | + nonce_xor[i-1] = iv0[i-1]; |
| 25 | + if (i - (int)(16 - sizeof(counter)) > (int)0) { |
| 26 | + nonce_xor[i-1] ^= (unsigned char)(counter >> ((16-i)*8)); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, nonce_xor, stream_block); |
| 31 | + if (ret != 0) { |
| 32 | + break; |
| 33 | + } |
| 34 | + counter++; |
| 35 | + } |
| 36 | + c = *input++; |
| 37 | + *output++ = (unsigned char) (c ^ stream_block[n]); |
| 38 | + |
| 39 | + n = (n + 1) & 0x0F; |
| 40 | + } |
| 41 | + |
| 42 | + return ret; |
| 43 | +} |
| 44 | + |
| 45 | +void decrypt(uint8_t* key4way, uint8_t* IV_OTPsalt, uint8_t* IV_public, uint8_t(*buf)[16], int nblk) { |
| 46 | + mbedtls_aes_context aes; |
| 47 | + |
| 48 | + uint32_t aes_key[8]; |
| 49 | + uint32_t* key4waywords = (uint32_t*)key4way; |
| 50 | + // Key is stored as a 4-way share of each word, ie X[0] = A[0] ^ B[0] ^ C[0] ^ D[0], stored as A[0], B[0], C[0], D[0] |
| 51 | + for (int i=0; i < count_of(aes_key); i++) { |
| 52 | + aes_key[i] = key4waywords[i*4] |
| 53 | + ^ key4waywords[i*4 + 1] |
| 54 | + ^ key4waywords[i*4 + 2] |
| 55 | + ^ key4waywords[i*4 + 3]; |
| 56 | + } |
| 57 | + |
| 58 | + uint8_t iv[16]; |
| 59 | + for (int i=0; i < sizeof(iv); i++) { |
| 60 | + iv[i] = IV_OTPsalt[i] ^ IV_public[i]; |
| 61 | + } |
| 62 | + |
| 63 | + int len = nblk * 16; |
| 64 | + |
| 65 | + mbedtls_aes_setkey_enc(&aes, (uint8_t*)aes_key, 256); |
| 66 | + |
| 67 | + lock_key(); |
| 68 | + |
| 69 | + uint8_t xor_working_block[16] = {0}; |
| 70 | + uint8_t stream_block[16] = {0}; |
| 71 | + size_t nc_off = 0; |
| 72 | + mb_aes_crypt_ctr_xor(&aes, len, (uint8_t*)iv, xor_working_block, stream_block, (uint8_t*)buf, (uint8_t*)buf); |
| 73 | +} |
0 commit comments