Reputation: 107
I'm currently working on a program that encrypt a file with AES-128 (with tiny-aes-c). I'm having a problem with the first array that contain \0 :
uint8_t in[16] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52};
uint8_t key[16] = "ABCDEFGHIJKLMNOP";
uint8_t iv[16] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, in, strlen((char*)in));
printf("\nENCODED: %s", (char*)in);
/*Another print for hex values*/
As expected, only the left part is encrypted and the rest disappear. How should I procede to correct this ? Thank you.
Upvotes: 1
Views: 236
Reputation: 316
You're using strlen(in)
which counts up to first nul byte (0x00), and in this case it returns 8 rather than the full length of the buffer (16).
To correct, determine the length of the buffer by other means. Here you already know that it's 16. You may use sizeof(in)
here, e.g.:
uint8_t in[16] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52};
uint8_t key[16] = "ABCDEFGHIJKLMNOP";
uint8_t iv[16] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, in, sizeof(in));
but this won't work if you rewrite the code for a variable length array. In that case you should pass the length as an extra parameter.
Upvotes: 3