Hello,
Here is some example code of me trying to decrypt a partial AES message. It
doesn't work.. is there a way I can do something like this? It only works if
I call DecryptMessage() with the entire encrypted string. Why?
Thanks!!
#include <openssl/evp.h>
#include <iostream>
#include <string>
using namespace std;
#pragma comment (lib, "libeay32MDd.lib")
EVP_CIPHER_CTX enCTX, deCTX;
int blockSize=128;
string DecryptMessage(const string message)
{
try
{
int p_len = message.length(), f_len = 0;
unsigned char* plaintext = (unsigned char*)malloc(p_len);
if(!EVP_DecryptInit_ex(&deCTX, NULL, NULL, NULL, NULL))
cerr << "ERROR in EVP_DecryptInit_ex" << endl;
if(!EVP_DecryptUpdate(&deCTX, plaintext, &p_len, (unsigned
char*)message.data(),
message.length()))
cerr << "ERROR in EVP_DecryptUpdate" << endl;
if(!EVP_DecryptFinal_ex(&deCTX, plaintext+p_len, &f_len))
cerr << "ERROR in EVP_DecryptFinal_ex" << endl;
return string((char*)plaintext, p_len + f_len-1);
}
catch(...)
{
return message;
}
}
string EncryptMessage(const string message)
{
try
{
// max ciphertext len for a n bytes of plaintext is n +
AES_BLOCK_SIZE bytes
int c_len = message.length() + blockSize;
unsigned char *ciphertext = (unsigned char*)malloc(c_len);
if(!EVP_EncryptInit_ex(&enCTX, NULL, NULL, NULL, NULL))
cerr << "ERROR in EVP_EncryptInit_ex" << endl;
// update ciphertext, c_len is filled with the length of ciphertext
generated
if(!EVP_EncryptUpdate(&enCTX, ciphertext, &c_len, (unsigned
char*)message.data(),
message.length()+1))
cerr << "ERROR in EVP_EncryptUpdate" << endl;
// update ciphertext with the final remaining bytes
int f_len = 0;
if(!EVP_EncryptFinal_ex(&enCTX, ciphertext+c_len, &f_len))
cerr << "ERROR in EVP_EncryptFinal_ex" << endl;
return string((char*)ciphertext, c_len + f_len);
}
catch(...)
{
return message;
}
}
int main()
{
// ssl init
const EVP_CIPHER* c = EVP_aes_128_cbc();
unsigned char key[32], iv[32];
string passphrase="test";
string salt="12345678";
int rounds=5;
EVP_BytesToKey(c, EVP_sha1(), (unsigned char*)salt.data(), (unsigned
char*)passphrase.data(), passphrase.length(), rounds, key, iv);
EVP_CIPHER_CTX_init(&deCTX);
EVP_DecryptInit_ex(&deCTX, c, NULL, key, iv);
EVP_CIPHER_CTX_init(&enCTX);
EVP_EncryptInit_ex(&enCTX, c, NULL, key, iv);
// trying to encrypt and decrypt
string plaintext = "0000015this is a test!";
cout << "plaintext: " << plaintext << endl;
string ciphertext = EncryptMessage(plaintext);
cout << "ciphertext: " << ciphertext << endl;
string header = ciphertext.substr(0, 7);
cout << "header: " << header << endl;
string decrypted_header = DecryptMessage(header);
cout << "decrypted header: " << decrypted_header << endl;
}