AES-ECB-128 encrypt/decrypt working inconsistently
Formosan opened this issue · 1 comments
Hi,
I wanted to implement the library for a project I'm working on, but I'm having an issue with the implementation. I'm not sure, if it's a bug in the code, my own misunderstanding of the algorithm, or some other issue entirely.
This is the sample of the code:
#define ENCRYPT_KEY { (uint8_t)0x2b, (uint8_t)0x7e, (uint8_t)0x15, (uint8_t)0x16, (uint8_t)0x28, (uint8_t)0xae, (uint8_t)0xd2, (uint8_t)0xa6,
(uint8_t)0xab, (uint8_t)0xf7, (uint8_t)0x15, (uint8_t)0x88, (uint8_t)0x09, (uint8_t)0xcf, (uint8_t)0x4f, (uint8_t)0x3c }void encryptAes(char* buffer, const short len, const char* str) {
size_t buffer_len = 0;
const unsigned char key[] = ENCRYPT_KEY;
memset(buffer, 0, len);
strncpy(buffer, str, len);
buffer_len = strlen(test_buffer);
AES_init_ctx(&ctx, key);
for (i = 0; i < buffer_len; i += 16)
{
AES_ECB_encrypt(&ctx, (uint8_t*)(buffer+i));
}
}
void decryptAes(char* buffer, const short len, const char* str, const short str_len) {
size_t buffer_len = 0;
const unsigned char key[] = ENCRYPT_KEY;
memset(buffer, 0, len);
strncpy(buffer, str, len);
buffer_len = strlen(buffer);
//buffer_len = str_len
AES_init_ctx(&ctx, key);
for (i = 0; i < buffer_len; i += 16)
{
AES_ECB_decrypt(&ctx, (uint8_t*)(buffer +i));
}
}
The issue is that for some strings passed to the function, it works perfectly. I add padding to the encrypted strings, so they always have 16 characters, or 32. However, in some cases, the decryption just breaks. Meaning, some of the strings passed are decrypted just fine, while from other decryption I get random characters. Even though I'm always using the same key. The issue exists regardless if I'm using the length of the original, unencrypted string or the encrypted one. Not sure how to handle the situation, changing the key only made it so different strings break, but they break nonetheless.
Hi @Formosan
I can't really see what you're trying to do as the code isn't formatted and it is incomplete.
It sounds like you're not properly padding your buffers before copying the strings, and that is a common problem when working with strings, that does not always fill the buffer size (blocks of 16 bytes).
There are very likely no bugs in the algorithm ECB-implementation you are using (which is discouraged).