2
votes

I'm trying to get a simple AES encrypt/decrypt going using c++ for my computer science class. It works almost perfectly, but the decryption will only work on the first 16 characters of the character array.

Here's my code:

#include <iostream>
#include "openssl/aes.h"

using namespace std;

int main() {
    unsigned char teext[] = "The quick brown fox jumped over the lazy dog";

    /*created keys for en- and de-cryption*/
    unsigned char key[] = "abcdefghijklmnop";
    unsigned char iv[] = "abcdefghijklmnop";

    /*char array for encryption and decryption output*/
    unsigned char enc_out[80];
    unsigned char dec_out[80];

    /*creating key variables*/
    AES_KEY enc_key, dec_key;

    /*encryption process*/
    AES_set_encrypt_key(key, 128, &enc_key);
    AES_encrypt(teext, enc_out, &enc_key);

    /*decryption process*/
    AES_set_decrypt_key(iv, 128, &dec_key);
    AES_decrypt(enc_out, dec_out, &dec_key);

    cout << "AES encryption"
         << "Encrypted: " << enc_out << endl 
         << "Decrypted: " << dec_out << endl;

    return 0;
}

I'm compiling with this:

 g++ Crypto.cc -L/usr/lib -lssl -lcrypto -o crypto

The program will encrypt "The quick brown fox jumped over the lazy dog" just fine. But when decrypting it outputs "The quick brown" and then random characters. Any idea what I'm doing wrong?

1
Possible duplicate of AES_encrypt/AES_decrypt only returns part of a message. Use the EVP_* interfaces as instructed in the cited duplicate. Don't use AES_encrypt and AES_decrypt.jww

1 Answers

3
votes

AES_decrypt just decrypts one block of 16 bytes of AES data. I believe it is a lower level function than what you want.

You're much better off using the EVP_* level functions instead. You can find a pretty complete example of how to use these on the openssl wiki - it's even using AES ecryption : https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption