Intermittent decryption failures in EVP_DecryptFinal_ex when using AES-128/CBC

倾然丶 夕夏残阳落幕 提交于 2019-12-12 05:27:26

问题


I am using the EVP library found here: https://www.openssl.org/docs/manmaster/crypto/EVP_EncryptInit.html

Here are my two encryption and decryption functions:

I am trying to encrypt a string using AES 128 CBC.

The string is usually of the format word1 word2 word3

char* encrypt(char *s, char *key) {
        unsigned char iv[16] = {[0 ... 15 ] = 0};
        unsigned char outbuf[1024] = {[0 ... 1023] = 0};
        int outlen1, outlen2;

        EVP_CIPHER_CTX ctx;

        EVP_CIPHER_CTX_init(&ctx);
        EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
        if (EVP_EncryptUpdate(&ctx, outbuf, &outlen1, s, strlen(s)) == 1) {
                if (EVP_EncryptFinal_ex(&ctx, outbuf + outlen1, &outlen2) == 1) {
                        EVP_CIPHER_CTX_cleanup(&ctx);
                        return strdup(outbuf);
                }
        }
        EVP_CIPHER_CTX_cleanup(&ctx);
        return NULL;
}

char* decrypt(char *s, char *key) {
        unsigned char iv[16] = {[0 ... 15 ] = 0};
        unsigned char outbuf[1024] = {[0 ... 1023] = 0};
        int outlen1, outlen2;

        EVP_CIPHER_CTX ctx;

        EVP_CIPHER_CTX_init(&ctx);
        EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
        if (EVP_DecryptUpdate(&ctx, outbuf, &outlen1, s, strlen(s)) == 1) {
                printf("After decrypt update\n");
                if (EVP_DecryptFinal_ex(&ctx, outbuf + outlen1, &outlen2) == 1) {
                        printf("After decrypt final\n");
                        EVP_CIPHER_CTX_cleanup(&ctx);
                        return strdup(outbuf);
                }
        }
        EVP_CIPHER_CTX_cleanup(&ctx);
        return NULL;
}

The problem is the decryption final function works on some strings but not on others.

If the string before it is encrypted is something like cat dog cow, the decryption works.

But if it is like bat dog cow, the decryption fails in particular at the EVP_DecryptFinal_ex() function.

For some strings, the decryption always fails at the EVP_DecryptFinal_ex() function. It does not return 1.

Any idea what the problem could be? Padding maybe? I just can't seem to figure it out.


回答1:


You probably miss that the encrypted string may contain zero-bytes, so the strlen(s) in DecryptUpdate has a too low value. You have to remember from encrypt how long the encrypted data is and use that value for decrypting.



来源:https://stackoverflow.com/questions/34096894/intermittent-decryption-failures-in-evp-decryptfinal-ex-when-using-aes-128-cbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!