I have an application that has to Encrypt data.
However, when I run the following it returns me different output within the same execution. When I repeat the execution, the pattern of output is exactly the same, see end of my question.
int Encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, key, iv)) {
handleErrors();
}
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
handleErrors();
}
ciphertext_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
handleErrors();
}
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
string EncryptThis(string Data, string Key, string IV, long long Buffer) {
unsigned char *key = (unsigned char *)Key.c_str();
unsigned char *iv = (unsigned char *)IV.c_str();
unsigned char *plaintext = (unsigned char *)Data.c_str();
unsigned char* ciphertext = new unsigned char[Buffer];
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
//cout << Data << endl; //ALWAYS THE SAME
//cout << Key << endl; //ALWAYS THE SAME
//cout << IV << endl; //ALWAYS THE SAME
int ciphertext_len = Encrypt(plaintext, (int)strlen((char *)plaintext), key, iv, ciphertext);
string Encrypted = base64_encode(reinterpret_cast<const unsigned char *>(ciphertext), ciphertext_len);
EVP_cleanup();
ERR_free_strings();
return Encrypted;
}
int main() {
cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
}
In this test the results where:
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
However, when I run the same application again, it returns me exact the same output even in the same order. So it seems to be a problem with the repetition within the execution of the script?
To clarify. When this application would be called Test.exe
and I execute the application three times, it would output the following:
//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
//Execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
How is this possible and where is my error?