You don’t write the crypto yourself. You include one file, seal the secret with AesHmacSeal, and get it back with AesHmacOpen, which returns the text only when the key is right and nobody changed a single character.
That file is AesHmac, an include library for MQL5 and MQL4, made for the secrets an expert, indicator or script has to keep around: an API token in a settings file, a licence string, a message two of your own programs pass through a file or a web request. A password or a 32-byte key goes in with the text or raw bytes, and out comes a base64 string you can write to a file or send. The wrong key, or one tampered character, gets you an error code instead of the text.
Where do I put the file?
In MQL5/Include/AesHmac/, or MQL4/Include/AesHmac/ on MT4. It’s AesHmac.mqh, it includes nothing else, and it’s free on the CodeBase, one entry per terminal: MetaTrader 5 and MetaTrader 4. File > Open Data Folder in the terminal gets you to the right place. Then:
#include <AesHmac\AesHmac.mqh>Making a key from a password, lifted from the example script that ships with it:
uchar key[];
int err = AesHmacKeyFromPassword(EXAMPLE_PASSWORD, EXAMPLE_SALT, AES_HMAC_DEFAULT_ITERATIONS, key);The password there is "my trading password" and the salt is "AesHmacExample". With the key in hand, AesHmacSeal(key, text, sealed) fills sealed with base64 and AesHmacOpen(key, sealed, text) fills text again. Every call that can fail returns AES_HMAC_OK or an error code. Check it. I’m not doing it for you.
Why not just call CryptEncode with CRYPT_AES256 and go home?
Because AES alone can’t tell you the message was changed. Flip a few bytes of an encrypted text and decrypting it still “works”. Your EA gets garbage back and cheerfully tries to log in with it as a token.
AesHmac puts a tag after the encrypted text. It’s an HMAC-SHA256, a 32-byte checksum that only someone holding the key can compute. AesHmacOpenBytes checks the tag before it decrypts anything. It compares all 32 bytes every time, because a check that quits at the first wrong byte tells an attacker, by its timing, how far they got:
// Compared in full, so the time taken does not say where it differs.
int difference = 0;
for(int i = 0; i < AES_HMAC_TAG_SIZE; i++)
{
difference |= expected[i] ^ sealed[size - AES_HMAC_TAG_SIZE + i];
}The terminal’s CRYPT_AES256 only gets used as the raw block cipher, one 16-byte block at a time, since MetaQuotes’ reference doesn’t say what the fuck it does to longer data. The library builds CTR mode on top of it in plain MQL. AES encrypts a counter, the result is XORed into your data 16 bytes at a time, and the counter goes up by one. Your key never touches the data directly. The library derives two keys from it, HMAC-SHA256 of your key with "encryption" and with "authentication", and the one that encrypts is never the one that tags.
What do I get when the password is wrong?
An error code, never garbage. The library has four of its own, numbered up from ERR_USER_ERROR_FIRST, past every code the terminal itself uses:
#define AES_HMAC_OK 0
#define AES_HMAC_ERROR_KEY (ERR_USER_ERROR_FIRST + 1)
#define AES_HMAC_ERROR_ARGUMENT (ERR_USER_ERROR_FIRST + 2)
#define AES_HMAC_ERROR_FORMAT (ERR_USER_ERROR_FIRST + 3)
#define AES_HMAC_ERROR_AUTH (ERR_USER_ERROR_FIRST + 4)AesHmacErrorText turns them into words: “the key must be 32 bytes”, “invalid argument”, “not a sealed message”, and “wrong key, or the message was changed”. A wrong key and a changed message share one error because the tag check can’t tell them apart. Text that isn’t base64, or decodes to fewer than 48 bytes, is “not a sealed message”. When CryptEncode itself fails you get the terminal’s GetLastError() code, which AesHmacErrorText reports as “terminal error” plus the number.
The example handles a refusal like this:
string text;
int err = AesHmacOpen(key, sealed, text);
if(err == AES_HMAC_OK)
{
PrintFormat("opened case=%s text=%s", name, text);
return;
}
PrintFormat("refused case=%s reason=\"%s\"", name, AesHmacErrorText(err));After any error, AesHmacSeal and AesHmacOpen leave "" and the byte versions leave an empty array. Your variable holds the whole secret or nothing at all, never half of one.
Will it piss all over my log? No. It prints nothing; the PrintFormat lines above are the example’s, not the library’s.
Why does the same text come out different every time?
Because every seal starts with a fresh 16-byte nonce, a number used once. Reusing a nonce with the same key in CTR mode is how people shoot their own crypto in the face: XOR the two encrypted texts and the key stream cancels out. AesHmacNonce hashes the previous nonce, a call counter, the local time, the microsecond and tick counters, the chart ID and three MathRand() calls with SHA-256, and keeps the first 16 bytes. The nonce isn’t secret. It rides in the clear at the front of the sealed message, and its only job is to never repeat. The example seals its secret twice and prints same_as_first=false.
How slow is the password thing?
14 ms on MT5 and 27 ms on MT4, at the default 10000 rounds, in the runs on the CodeBase pages. AesHmacKeyFromPassword runs PBKDF2-HMAC-SHA256, which hashes the password over and over, so every guess costs whoever’s guessing the same grind. AES_HMAC_DEFAULT_ITERATIONS is that 10000. More rounds slow the bastard down, and you with him. Fewer than 1 is AES_HMAC_ERROR_ARGUMENT.
The salt doesn’t need to be secret. Give each program its own, and the same password makes a different key in each one. Already have 32 random bytes? Skip the password and pass them as the key. Any other length is AES_HMAC_ERROR_KEY.
Can I seal bytes instead of a string?
Yes, with AesHmacSealBytes and AesHmacOpenBytes, which take uchar arrays. A sealed message is the 16-byte nonce, the encrypted data at the same length as yours, and the 32-byte tag, 48 bytes more than what went in. The string pair is a wrapper around those two. Text goes in as UTF-8, so any language survives, and comes out as base64. An empty string seals and opens back to an empty string.
The parts are public too: AesHmacEncryptBlock for one AES-256 block, AesHmacCtr for CTR mode (the same call decrypts), AesHmacMac, AesHmacPbkdf2, AesHmacSha256, and the helpers AesHmacFromHex, AesHmacToHex and AesHmacUtf8.
How do I know your crypto isn’t broken?
It checks itself against published test values before it does anything else. The example script, AesHmacExample, tests the AES block and CTR mode against NIST SP 800-38A, the US standards body’s AES examples, HMAC against test case 2 of RFC 4231, and PBKDF2 against section 11 of RFC 7914. One wrong answer and it prints FAILED and stops right there.
After that it makes a key, seals a JSON secret twice, writes it to MQL5\Files\AesHmac\secret.txt, reads it back and opens it. Then it tries three things that have to fail: a password with one character different, the sealed text with one character changed, and hello world, which was never sealed at all.
Run it yourself, though. Taking a stranger’s crypto on faith is a dumbass habit. AesHmacExample.mq5 goes in MQL5/Scripts (AesHmacExample.mq4 in MQL4/Scripts). Compile it in MetaEditor, start it on a chart, and the results land in the Experts tab.

Is the MT4 one some crippled port?
No. The MQL4 quirks are handled inside the code, like this one:
//--- An empty message has nothing to decrypt. ArrayCopy is not called with a
//--- count of 0: MQL4's WHOLE_ARRAY is 0 and would copy the tag as well.
if(cipherSize == 0)
{
return AES_HMAC_OK;
}Miss that and an empty secret opens as 32 bytes of tag on MT4 only, a bug you’d chase for a week while your MT5 tests pass, smug as hell. AesHmac.mqh is one file, the same in both downloads, so the fix lives in one place.
Can someone still dig the key out of my compiled program?
Yes. A key or password compiled into a program keeps out other programs and anyone editing your files. It doesn’t keep out someone who takes the program apart.
AesHmac is a free download from the MQL5 CodeBase for MetaTrader 5 and MetaTrader 4: one include file and an example script that tests itself first.