Watch how to download trading robots for free
Find us on Facebook!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Libraries

AesHmac: AES-256 encryption with tamper check and password keys for MQL4 - library for MetaTrader 4

George Ciprian Mandache
George Ciprian Mandache
Mostly writing code that does stuff...
Views:
73
Rating:
(1)
Published:
\MQL4\Include\AesHmac\
AesHmac.mqh (21.99 KB) view
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

AesHmac encrypts texts and bytes in MQL4 so that only a program holding the same key can read them. It is one include file with no other dependencies, built on the terminal's own CryptEncode. Use it for an API token in a settings file, a licence string, or a message two of your programs pass through a file or a web request.

Encryption alone does not tell you whether someone changed the message. AesHmac adds a tag that does: a wrong key, one changed character or text that was never sealed is refused with an error code, never decrypted into garbage that your program then tries to use.

#include <AesHmac\AesHmac.mqh>

Features

  • AES-256 in CTR mode with a fresh random nonce for every message, so sealing the same text twice gives two different results.
  • An HMAC-SHA256 tag over the nonce and the encrypted text, checked over its full length before anything is decrypted.
  • Separate keys for encrypting and for the tag, both derived from the key you give.
  • Keys from a password with PBKDF2-HMAC-SHA256: 10000 rounds by default, which took 27 ms in the run in the picture.
  • Text goes in and comes out as UTF-8, so any language survives. The sealed text is base64, safe in a file, a global variable or a URL parameter. Bytes work too.
  • Checked against official test vectors: NIST SP 800-38A for AES-256 (block and CTR mode), all seven cases of RFC 4231 for HMAC-SHA256 and RFC 7914 for PBKDF2. The example script runs a self test against them first.
  • A message sealed by Python's cryptography package with the same steps opens in MQL4.
  • Every call that can fail returns AES_HMAC_OK or an error code, and AesHmacErrorText says what it means. The library never prints anything by itself.

Example

#include <AesHmac\AesHmac.mqh>

void OnStart() {
    uchar key[];
    if (AesHmacKeyFromPassword("a long password", "MyEA", AES_HMAC_DEFAULT_ITERATIONS, key) != AES_HMAC_OK) {
        return;
    }

    string sealed;
    AesHmacSeal(key, "{\"api_token\":\"tk_5f2c9a71\"}", sealed);
    Print(sealed);                           // base64, different every time

    string text;
    int err = AesHmacOpen(key, sealed, text);
    if (err != AES_HMAC_OK) {
        Print("refused: ", AesHmacErrorText(err));
        return;
    }
    Print(text);                             // {"api_token":"tk_5f2c9a71"}
}

The attached AesHmacExample script runs the self test, makes a key from a password, seals a secret twice, saves it to MQL4\Files\AesHmac\secret.txt, reads it back and opens it, then shows the three refusals:

self test aes_block=ok ctr=ok hmac=ok pbkdf2=ok
key made iterations=10000 ms=27
sealed again same_as_first=false
saved and opened file=AesHmac\secret.txt text={"api_token":"tk_5f2c9a71","server":"demo"}
refused case=wrong_password reason="wrong key, or the message was changed"
refused case=one_character_changed reason="wrong key, or the message was changed"
refused case=not_sealed reason="not a sealed message"

The picture is a real run on a MetaTrader 4 demo account.

The Experts log of the example on MetaTrader 4: self test, key, sealed text, the file opened and the three refusals

API

Call What it does
AesHmacKeyFromPassword(password, salt, iterations, key) Make a 32-byte key from a password; use one salt per program
AesHmacSeal(key, text, sealed), AesHmacOpen(key, sealed, text) Seal a text into base64 and open it again
AesHmacSealBytes(key, plain, sealed), AesHmacOpenBytes(key, sealed, plain) The same for bytes; a sealed message is 48 bytes longer than the plain one
AesHmacErrorText(code) Describe an error code
AesHmacEncryptBlock(key, plain, cipher), AesHmacCtr(key, counter, source, output) One AES-256 block, and AES-256 in CTR mode (the same call decrypts)
AesHmacMac(key, data, mac), AesHmacPbkdf2(password, salt, iterations, size, key), AesHmacSha256(data, hash) HMAC-SHA256, PBKDF2-HMAC-SHA256 and SHA-256
AesHmacFromHex(hex, bytes), AesHmacToHex(bytes), AesHmacUtf8(text, bytes) Hex and UTF-8 helpers

A key compiled into a program keeps out other programs and edited files, not someone who takes the program apart.

TesterSafeLots - risk lot size that stays correct in the MT4 Strategy Tester TesterSafeLots - risk lot size that stays correct in the MT4 Strategy Tester

Risk-based lot size for MQL4 that does not depend on MODE_TICKVALUE in the Strategy Tester, so backtests of USDJPY, USDCHF or USDCAD on a USD account risk what the input says. Includes a test EA that measures the error.

Hotkeys: keyboard shortcuts for MQL4 experts and indicators, set in the inputs Hotkeys: keyboard shortcuts for MQL4 experts and indicators, set in the inputs

One include file that gives your EA or indicator keyboard shortcuts the user types into the inputs, such as Shift+B. Each press fires one action, Shift+B never fires on a plain B, and a shortcut that cannot work is refused at start with the reason.

Three Colors Three Colors

Example: Moving Average indicator filling by different colors

MACD Sample MACD Sample

Classical MACD Sample.