Greetings, and happy new(-ish) year,
I have an application that's using AES in CTR mode, and I've been working with it for quite a while (thankfully not in production yet) just assuming that my encryption was working. I feel like I've tested it before but it would have been a few weeks ago. In any case, I was recently doing some verification tests and found that my AES-encrypted data was not being decrypted properly, and now as far as I can tell CTR mode just isn't working properly. To confirm it wasn't just a problem elsewhere in my code I wrote a simple test program almost exactly following the docs here:
https://www.wolfssl.com/wolfSSL/Docs-wo … i-aes.html (under wc_AesCtrEncrypt).
To be clear, my exact test code is as follows:
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/aes.h>
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/random.h>
#include <stdio.h>
int main(void) {
byte msg[16] = "abcdefghijklmnop";
byte cipher[16];
byte decrypted[16];
Aes enc_dec;
RNG rng;
int idx;
byte *key = malloc(32);
byte *iv = malloc(16);
wc_InitRng(&rng);
wc_RNG_GenerateBlock(&rng, key, 32);
wc_RNG_GenerateBlock(&rng, iv, 32);
if(wc_AesSetKeyDirect(&enc_dec, key, 32, iv, AES_ENCRYPTION) < 0) {
printf("Error setting key\n");
return -1;
}
wc_AesCtrEncrypt(&enc_dec, cipher, msg, sizeof(msg));
wc_AesCtrEncrypt(&enc_dec, decrypted, cipher, sizeof(cipher));
for (idx = 0; idx < 16; idx++) {
printf("%c", (char)decrypted[idx]);
}
printf("\n");
return 0;
}
I would expect `decrypted` to contain the original message, but instead it just prints gibberish. Am I missing something obvious?