crypt.encrypt
Encrypts data using AES with the specified key and mode.
function crypt.encrypt(data: string, key: string, iv: string?, mode: string?): (string, string)Synopsis
How it works
Encrypts plaintext using AES-256 symmetric encryption. All keys and IVs are Base64-encoded. If no IV is provided, a 16-byte random IV is generated from the system CSPRNGCSPRNGCryptographically Secure Pseudo-Random Number Generator. Produces output indistinguishable from true randomness. OS implementations: BCryptGenRandom (Windows), getrandom (Linux), /dev/urandom (Unix). and returned as the second value.
AES-256-CBC internals
The default mode is AES-256-CBCAES-256-CBCAdvanced Encryption Standard with a 256-bit key in Cipher Block Chaining mode. Each 16-byte plaintext block is XORed with the previous ciphertext block before encryption. Requires an IV (Initialization Vector) for the first block. (Cipher Block Chaining):
- Plaintext is padded to a 16-byte block boundary using PKCS#7PKCS#7 paddingA padding scheme that fills the last block to the required size (16 bytes for AES). If 3 bytes are needed, appends 0x03 0x03 0x03. The pad value equals the number of padding bytes.
- Each 16-byte plaintext block is XORed with the previous ciphertext block (or IV for the first block)
- The XORXOR (exclusive OR)A bitwise operation: output is 1 only when inputs differ. Fundamental to encryption — CBC mode XORs each plaintext block with the previous ciphertext block before AES encryption. Reversible: A XOR B XOR B = A. result is encrypted with the 256-bit key through 14 rounds of AES (SubBytes, ShiftRows, MixColumns, AddRoundKey)
C₀ = IV
Cᵢ = AES_K(Pᵢ ⊕ Cᵢ₋₁) for i = 1..n
The 256-bit key (32 bytes, Base64-encoded to 44 chars) is expanded into 15 round keys (240 bytes) via the AES key schedule. The 128-bit IV (16 bytes) ensures identical plaintexts produce different ciphertexts.Security
Never reuse an IV with the same key — in CBCCBC modeCipher Block Chaining — an AES block mode where each plaintext block is XORed with the previous ciphertext block before encryption. Requires an IV for the first block. Provides better diffusion than ECB mode. mode, identical plaintext blocks at the same position will produce identical ciphertext blocks, leaking structural information. Use
crypt.generatekey() for keys and let the function generate a fresh IV. Supported modes: CBC (default), ECB (no IV, insecure), CTR, CFB, OFB, GCM.Usage
Encrypt / decrypt
local key = crypt.generatekey()
local ciphertext, iv = crypt.encrypt("secret data", key)
local plaintext = crypt.decrypt(ciphertext, key, iv)
print(plaintext) "cc">--> secret dataParameters
data string Plaintext to encrypt.
key string Base64-encoded 256-bit key.
iv string optionalBase64-encoded AES IV. Auto-generated if omitted.
mode string optionalCipher mode (default "CBC").
Returns
string Base64-encoded ciphertext.
string Base64-encoded IV used.