Complete Encrypt + Decrypt cycle using AES256

 

wanted : encrypt a string using AES256 method, format the encrypted data into hexadecimal string, then decrypt it again using same key into the original string.


here's my try

uchar src[], dst[], key[];
string Original_text = "bla bla bla";
string SKey = "012345678901234567890123456789AB";
string Encrypted = "";
StringToCharArray(Original_text, src);
StringToCharArray(SKey, key);
if(CryptEncode(CRYPT_AES256, src, key, dst)<0) { Print("ERROR_1"); return; }
int count = ArraySize(dst);
for(int i=0; i<count; i++) Encrypted += StringFormat("%X", dst[i]);
Print(Encrypted);

which prints : 61CB5825C0A9B5BE56A3372F0A6EDF all ok.

now to decrypt (not from the dst char array above, but from the Encrypted string) :

uchar src2[], dst2[];
StringToCharArray(Encrypted, src2);
if(CryptDecode(CRYPT_AES256, src2, key, dst2)<0) { Print("ERROR_2"); return; }
string Decrypted_S = CharArrayToString(dst2);
Print(Decrypted_S);

I know the problem is when I format the dst array into Encrypted variable, I can't correctly revert it back to the char array before decryption.

how do I solve this problem ?


Documentation on MQL5: Common Functions / CryptEncode
Documentation on MQL5: Common Functions / CryptEncode
  • www.mql5.com
CryptEncode - Common Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
dandybandy:

wanted : encrypt a string using AES256 method, format the encrypted data into hexadecimal string, then decrypt it again using same key into the original string.


here's my try

which prints : 61CB5825C0A9B5BE56A3372F0A6EDF all ok.

now to decrypt (not from the dst char array above, but from the Encrypted string) :

I know the problem is when I format the dst array into Encrypted variable, I can't correctly revert it back to the char array before decryption.

how do I solve this problem ?


Instead of converting to a hex string, use CryptEncode to encode the result into base64.

This can be printed as string, and can be decided from base64 back, so you can go through without complex conversion.
Reason: