Cryptography Basics for MQL5 Developers

Cryptography Basics for MQL5 Developers
Cryptography is a must-know for MQL5 developers who want to secure trading strategies, API keys, and sensitive data. It ensures confidentiality, integrity, and protection from tampering. Here’s what you need to know:
- MQL5's Built-In Tools: Use
CryptEncodeandCryptDecodefor AES encryption (AES128, AES256) and hashing (MD5, SHA256). - Key Techniques:
- Symmetric Encryption: Fast and ideal for encrypting sensitive data.
- Hashing: Ensures data integrity but isn't reversible.
- Asymmetric Encryption: Not natively supported in MQL5 but can be implemented for added security.
- Common Use Cases:
- Protecting trading logic in Expert Advisors.
- Encrypting API credentials during communication.
- Verifying file integrity with hashing.
- Limitations: MQL5 lacks support for RSA and HMAC-SHA256, requiring custom implementations for advanced needs.
To maximize security, combine AES for data encryption with SHA256 for integrity checks. For advanced setups, hybrid encryption (RSA + AES) secures session keys and data efficiently. Avoid common pitfalls like incorrect key lengths and mismatched padding modes when integrating with external systems.
Cryptography isn't optional in automated trading - it’s a core part of protecting your algorithms and data.
Things you need to know about using encryption in Metatrader programming
sbb-itb-3b27815
Built-In Cryptographic Functions in MQL5

MQL5 provides two key functions for handling data securely: CryptEncode, which supports encryption, hashing, and compression, and CryptDecode, which handles decryption and decompression tasks. These functions work with uchar arrays, so you'll need to convert strings or data structures into this format before using them.
ENUM_CRYPT_METHOD Options in MQL5
MQL5 offers a variety of cryptographic methods, each with its own key requirements, output sizes, and operations. Here's a quick breakdown:
| Method | Type | Key Required | Key/Output Size |
|---|---|---|---|
CRYPT_BASE64 |
Encoding | No | ~133% of source |
CRYPT_DES |
Encryption | Yes | 7 bytes (56-bit) |
CRYPT_AES128 |
Encryption | Yes | 16 bytes (128-bit) |
CRYPT_AES256 |
Encryption | Yes | 32 bytes (256-bit) |
CRYPT_HASH_MD5 |
Hashing | No | 16 bytes |
CRYPT_HASH_SHA1 |
Hashing | No | 20 bytes |
CRYPT_HASH_SHA256 |
Hashing | No | 32 bytes |
CRYPT_ARCH_ZIP |
Compression | Optional* | Variable |
*For compatibility with external ZIP tools, use a 4-byte key {1, 0, 0, 0}.
If you want to automate trading ideas without manual coding, For most trading automation scenarios, CRYPT_AES256 is the go-to option for encrypting sensitive data, while CRYPT_HASH_SHA256 is commonly used for data integrity checks. However, keep in mind that CRYPT_DES is outdated and no longer aligns with modern security standards.
Encryption and Decryption Workflow in MQL5
The encryption process in MQL5 involves a few straightforward steps. First, convert your plaintext into a uchar array using the StringToCharArray function. Then, pass this array along with a key to CryptEncode to generate the ciphertext. To decrypt, reverse the process by using CryptDecode with the same key.
When working with AES and DES in MQL5, the platform uses ECB mode with zero padding. This means the input data must be a multiple of the block size (16 bytes for AES) for compatibility with external systems. After encrypting, you can compute a CRYPT_HASH_SHA256 of the ciphertext to ensure integrity. This hash can then be verified after decryption to confirm the data hasn't been tampered with.
Common Pitfalls with MQL5 Cryptographic Functions
To effectively secure your trading scripts, it's crucial to understand and avoid common mistakes. One frequent issue arises from the null terminator added by StringToCharArray, which can lead to incorrect hashes or problems during decryption. You can fix this by resizing the array with ArrayResize(data, ArraySize(data) - 1) before passing it to cryptographic functions.
Another common error involves incorrect key lengths. If the key array is too short, CryptEncode will fail, returning 0 and setting _LastError to INVALID_ARRAY. Always ensure your key matches the required length for the selected method.
Lastly, there’s a notable limitation with MQL5's CRYPT_HASH_SHA256. It performs a standard hash but doesn’t support HMAC-SHA256, which is often required for signing requests in exchange APIs. As Abdulkudus Okatengwu Kadir explains:
"Discrepancies in signature generation can cause valid trading signals and strategies to fail."
For such cases, you'll need to implement a custom HMAC wrapper to meet the API's requirements instead of relying on the built-in hash function.
Advanced Cryptographic Techniques in MQL5
Hybrid Encryption Workflow in MQL5: RSA + AES Step-by-Step
MQL5 offers built-in cryptographic functions, but advanced methods like RSA and hybrid encryption can significantly boost script security.
RSA Encryption in MQL5
MQL5 doesn’t natively support RSA encryption, so implementing it requires custom big-integer arithmetic using uchar arrays in big-endian format. Since MetaTrader Market products prohibit external DLLs, you’ll need to handle RSA entirely within MQL5. At its core, RSA relies on a modular exponentiation function (commonly called ModExp) to compute (base^exp) % mod efficiently using repeated squaring. Supporting functions like modular multiplication (MulMod), long division (Mod), and zero-byte stripping for uchar arrays are also essential for accuracy.
An RSA public key is defined by a modulus (n) and a public exponent (e). The public exponent is almost always set to 65537 for efficiency and security. When encrypting data, PKCS#1 v1.5 padding must be applied. This padding adds at least 11 bytes of randomness to ensure that identical plaintexts produce different ciphertexts, protecting against replay attacks. As Niara Patterson from Microsoft highlighted:
"1024-bit key lengths today provide insufficient security given the advancement of computing power and cryptanalysis techniques."
To meet modern security needs, RSA keys should be at least 2048 bits long. Keys shorter than this are no longer considered secure.
Given RSA's limitations, hybrid encryption offers a practical solution for encrypting large datasets, as explained in the next section.
Hybrid Encryption: Combining RSA and AES
RSA alone isn’t ideal for encrypting large amounts of data due to its computational demands and size constraints. Instead, a hybrid approach combines RSA and AES to leverage the strengths of both. In this setup, RSA secures a small AES session key, and AES handles the actual data encryption using MQL5’s built-in CryptEncode function with CRYPT_AES256.
Here’s how hybrid encryption typically works:
- Step 1: Generate a random 256-bit AES session key within your Expert Advisor.
- Step 2: Use the server’s RSA public key to encrypt the AES session key.
- Step 3: Encrypt your trading data with the AES key using
CryptEncode. - Step 4: Transmit the RSA-encrypted session key and the AES-encrypted data to the server.
As MQL5 developer Saif Akhlaq notes:
"RSA functions as the key protector, and AES functions as the data protector. Together, they form the foundation of modern secure communication protocols."
This method avoids hardcoding AES keys into your script. Since the AES key is generated fresh for each session and encrypted with RSA, intercepted ciphertext remains useless without the server’s private RSA key.
The table below highlights the key differences between RSA and AES:
| Feature | RSA (Asymmetric) | AES (Symmetric) |
|---|---|---|
| Speed | Slow, computationally heavy | Fast, optimized for bulk data |
| Best Use Case | Encrypting the session key | Encrypting the actual payload |
| MQL5 Support | Requires custom implementation | Built-in via CryptEncode |
| Key Management | Public/private key pair | Single shared secret |
| Recommended Size | 2048 bits or higher | 128 or 256 bits |
When implementing this approach, ensure compatibility between your MQL5 script and the external system it communicates with (e.g., a server in C# or Python). Both sides must agree on encryption modes and padding schemes. Note that MQL5’s CryptEncode function defaults to ECB mode with zero padding, which might differ from the settings used by external systems.
Best Practices for Cryptographic Security in MQL5
Key Management and Storage
Never hardcode encryption keys. Instead, store them securely using encrypted files or retrieve them remotely through secure channels. When sharing keys with clients, always use a secure messaging service - email is not a safe option. As Sahil Bagdi emphasizes:
"Key management is critical. The key must be securely generated and shared with clients using a secure channel... Never send the key via email."
Padding and Mode Considerations
Once your keys are securely managed, the next step is configuring the proper encryption mode and padding. MQL5's built-in AES and DES implementations default to ECB mode with zeros padding. While this setup is straightforward, ECB mode is weak because it produces identical ciphertext blocks for identical plaintext blocks, potentially exposing patterns in your data.
When integrating MQL5 with external systems like C# or Python, you may encounter a "Padding is incorrect" error. This happens because many libraries default to PKCS#7 or PKCS#5 padding, which differs from MQL5's zeros padding. To resolve this, adjust your external library settings to use PaddingMode.Zeros and CipherMode.ECB, aligning them with MQL5's behavior.
Here's a quick comparison of MQL5 defaults versus standard external libraries:
| Feature | MQL5 Default | Standard External Libraries |
|---|---|---|
| Encryption Mode | ECB | CBC or GCM |
| Padding Scheme | Zeros Padding | PKCS#7 or PKCS#5 |
| IV Requirement | Not used in ECB | Required for CBC/CFB/OFB |
Additionally, if you’re using CRYPT_ARCH_ZIP, keep in mind that MQL5 adds two header bytes and four Adler32 checksum bytes to the output. This makes it incompatible with standard ZIP tools. To bypass these extra bytes, use the key array {1, 0, 0, 0}.
Balancing Performance and Security
AES is much faster than RSA, making it the better choice for encrypting runtime data, especially in high-frequency trading scenarios. When deciding between AES-128 and AES-256, consider your priorities. AES-128, with a 16-byte key, offers better speed, while AES-256, with a 32-byte key, provides stronger protection for sensitive information. For most trading scripts, AES-256 is the safer option.
To optimize performance, encrypt only the most sensitive fields and use SHA-256 for integrity checks. When transmitting encrypted binary data over text-based protocols like JSON, encode it with CRYPT_BASE64 to avoid corruption during transit.
Conclusion: Strengthening MQL5 Scripts with Cryptography
Cryptography isn't just an optional feature for MQL5 scripts - it’s a crucial safeguard for protecting trading logic, API credentials, and signal data. With MQL5's built-in tools, you can apply essential cryptographic techniques without relying on external DLLs, making it easier to enhance security.
To maximize protection, consider a hybrid approach: use AES-256 for fast and efficient bulk encryption and SHA-256 to verify data integrity. Since MQL5 doesn’t include native RSA support, you can implement RSA manually to secure AES session keys. This synergy between RSA and AES is a well-established standard:
"RSA functions as the key protector, and AES functions as the data protector. Together, they form the foundation of modern secure communication protocols."
Pay special attention to function return values, such as those from CryptEncode and CryptDecode. A return value of 0 usually signals a failure, often due to an incorrect key length - AES-256, for instance, requires a key that’s exactly 32 bytes long . Overlooking such details could quietly undermine your encryption efforts.
As cryptography experts remind us:
"Cryptographic strength should be commensurate with the lifetime of the secret... If a fast flow of secure messages is required, shorter keys that are updated regularly will provide better performance."
Ultimately, robust cryptography is the cornerstone of reliable and secure MQL5 automation. By applying these principles carefully, you can ensure both the safety and efficiency of your trading systems.
FAQs
How do I choose between AES-128 and AES-256 in MQL5?
When deciding between AES-128 and AES-256, it all comes down to what you prioritize - security or speed. AES-256 delivers higher levels of encryption, making it a great choice for safeguarding highly sensitive data or for scenarios requiring long-term security. However, it does come with a performance cost, running about 20% slower than AES-128.
On the other hand, AES-128 strikes a balance by offering strong encryption while maintaining faster performance. This makes it a practical option for most MQL5 applications. For general purposes, AES-128 gets the job done efficiently. But if you're handling extremely sensitive information and can afford the slight performance dip, AES-256 is the way to go.
How can I make MQL5 AES work with my C# or Python server?
To make MQL5 AES encryption compatible with your C# or Python server, it's essential to align encryption parameters such as the AES mode, padding scheme, key, and initialization vector (IV).
For Python, libraries like PyCryptodome are excellent tools for handling AES encryption. In C#, you can rely on the cryptography tools provided by the .NET framework. Ensure that the key and IV are synchronized as byte arrays, and use the same encoding method (e.g., UTF-8) across both platforms. By maintaining consistent settings, you can ensure smooth encryption and decryption between MQL5 and your server.
How can I use HMAC-SHA256 or RSA in MQL5 without DLLs?
To use HMAC-SHA256 or RSA in MQL5 without relying on DLLs, you can either write custom code or modify existing examples from the MQL5 community. For HMAC-SHA256, building the algorithm from the ground up is possible, though it requires a solid understanding of cryptographic principles. Similarly, RSA encryption can be fully implemented in MQL5 with custom scripting.
While MQL5 includes functions like CryptEncode and CryptDecode for certain cryptographic operations, these tools might not cover every specific use case, making custom solutions necessary in some scenarios.