Skip to content

Commit 69933c9

Browse files
committed
Add IV XOR code, but turn it off with IV0_XOR for now
1 parent ab3ea10 commit 69933c9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

bintool/mbedtls_wrapper.c

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,56 @@ void mb_sha256_buffer(const uint8_t *data, size_t len, message_digest_t *digest_
4040
mbedtls_sha256(data, len, digest_out->bytes, 0);
4141
}
4242

43+
#if IV0_XOR
44+
// Taken from mbedtls_aes_crypt_ctr, but with XOR instead of adding to IV0
45+
int mb_aes_crypt_ctr_xor(mbedtls_aes_context *ctx,
46+
size_t length,
47+
unsigned char iv0[16],
48+
unsigned char nonce_xor[16],
49+
unsigned char stream_block[16],
50+
const unsigned char *input,
51+
unsigned char *output)
52+
{
53+
int c;
54+
int ret = 0;
55+
size_t n = 0;
56+
size_t counter = 0;
57+
58+
while (length--) {
59+
if (n == 0) {
60+
for (int i = 16; i > 16 - sizeof(counter); i--) {
61+
nonce_xor[i-1] == iv0[i-1] ^ (unsigned char)(counter >> (i*8));
62+
}
63+
64+
ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, nonce_xor, stream_block);
65+
if (ret != 0) {
66+
break;
67+
}
68+
}
69+
c = *input++;
70+
*output++ = (unsigned char) (c ^ stream_block[n]);
71+
72+
n = (n + 1) & 0x0F;
73+
}
74+
75+
return ret;
76+
}
77+
#endif
78+
4379
void mb_aes256_buffer(const uint8_t *data, size_t len, uint8_t *data_out, const aes_key_t *key, iv_t *iv) {
4480
mbedtls_aes_context aes;
4581

4682
assert(len % 16 == 0);
4783

4884
mbedtls_aes_setkey_enc(&aes, key->bytes, 256);
85+
uint8_t xor_working_block[16] = {0};
4986
uint8_t stream_block[16] = {0};
5087
size_t nc_off = 0;
88+
#if IV0_XOR
89+
mb_aes_crypt_ctr_xor(&aes, len, iv->bytes, xor_working_block, stream_block, data, data_out);
90+
#else
5191
mbedtls_aes_crypt_ctr(&aes, len, &nc_off, iv->bytes, stream_block, data, data_out);
92+
#endif
5293
}
5394

5495
void raw_to_der(signature_t *sig) {

bintool/mbedtls_wrapper.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ extern "C" {
1717
#include <mbedtls/ecp.h>
1818
#include <mbedtls/aes.h>
1919

20+
/*
21+
* Use XOR of counter with IV0 to generate the IV for each encrypted block
22+
*
23+
* ie IV = IV0 ^ block_number, rather than the default IV = IV0 + block_number
24+
*
25+
* The power signature for this calculation is easier to mask on RP2350 than
26+
* adding the block number to the IV0
27+
*/
28+
#define IV0_XOR 0
29+
2030
#ifdef __cplusplus
2131
#define _Static_assert static_assert
2232
#endif

0 commit comments

Comments
 (0)