Kingamere
Kingamere

Reputation: 10112

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

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.

Upvotes: 1

Views: 1090

Answers (1)

Ctx
Ctx

Reputation: 18410

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.

Upvotes: 1

Related Questions