Skip to content

Commit

Permalink
Add IV XOR code, but turn it off with IV0_XOR for now
Browse files Browse the repository at this point in the history
  • Loading branch information
will-v-pi committed Feb 19, 2025
1 parent ab3ea10 commit 69933c9
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
41 changes: 41 additions & 0 deletions bintool/mbedtls_wrapper.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,56 @@ void mb_sha256_buffer(const uint8_t *data, size_t len, message_digest_t *digest_
mbedtls_sha256(data, len, digest_out->bytes, 0);
}

#if IV0_XOR
// Taken from mbedtls_aes_crypt_ctr, but with XOR instead of adding to IV0
int mb_aes_crypt_ctr_xor(mbedtls_aes_context *ctx,
size_t length,
unsigned char iv0[16],
unsigned char nonce_xor[16],
unsigned char stream_block[16],
const unsigned char *input,
unsigned char *output)
{
int c;
int ret = 0;
size_t n = 0;
size_t counter = 0;

while (length--) {
if (n == 0) {
for (int i = 16; i > 16 - sizeof(counter); i--) {
nonce_xor[i-1] == iv0[i-1] ^ (unsigned char)(counter >> (i*8));
}

ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, nonce_xor, stream_block);
if (ret != 0) {
break;
}
}
c = *input++;
*output++ = (unsigned char) (c ^ stream_block[n]);

n = (n + 1) & 0x0F;
}

return ret;
}
#endif

void mb_aes256_buffer(const uint8_t *data, size_t len, uint8_t *data_out, const aes_key_t *key, iv_t *iv) {
mbedtls_aes_context aes;

assert(len % 16 == 0);

mbedtls_aes_setkey_enc(&aes, key->bytes, 256);
uint8_t xor_working_block[16] = {0};
uint8_t stream_block[16] = {0};
size_t nc_off = 0;
#if IV0_XOR
mb_aes_crypt_ctr_xor(&aes, len, iv->bytes, xor_working_block, stream_block, data, data_out);
#else
mbedtls_aes_crypt_ctr(&aes, len, &nc_off, iv->bytes, stream_block, data, data_out);
#endif
}

void raw_to_der(signature_t *sig) {
Expand Down
10 changes: 10 additions & 0 deletions bintool/mbedtls_wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ extern "C" {
#include <mbedtls/ecp.h>
#include <mbedtls/aes.h>

/*
* Use XOR of counter with IV0 to generate the IV for each encrypted block
*
* ie IV = IV0 ^ block_number, rather than the default IV = IV0 + block_number
*
* The power signature for this calculation is easier to mask on RP2350 than
* adding the block number to the IV0
*/
#define IV0_XOR 0

#ifdef __cplusplus
#define _Static_assert static_assert
#endif
Expand Down

0 comments on commit 69933c9

Please sign in to comment.