Cryptography

crypt.encrypt

Encrypts Lua string bytes with AES CBC, ECB, or CTR using a Base64-decoded key, then returns Base64 ciphertext and the IV result.

Syntax

crypt.encrypt(data: string, key: string, iv?: string, mode?: "CBC" | "ECB" | "CTR" | "AES-CBC" | "AES-ECB" | "AES-CTR"): string | string | nil

Arguments

NameTypeDescription
datastringPlaintext bytes read from a Lua string.
keystringBase64 key decoded before it is passed to AES.
iv?stringOptional Base64 IV for CBC or CTR. When omitted for CBC or CTR, a new AES block-size IV is generated.
mode?"CBC" | "ECB" | "CTR" | "AES-CBC" | "AES-ECB" | "AES-CTR"AES mode. The AES- prefix is removed when present. Defaults to AES-CBC. CBC and ECB use crypto library DEFAULT_PADDING; CTR uses no padding.

Returns

NameTypeDescription
ciphertextstringBase64-encoded ciphertext.
initializationVectorstring | nilBase64-encoded IV for CBC and CTR; nil for ECB.

Description

Encrypts Lua string bytes with AES CBC, ECB, or CTR using a Base64-decoded key, then returns Base64 ciphertext and the IV result.

Call it with 4 parameter(s): data, key, iv, mode. The argument table explains which values are required and which ones only refine the behavior.

It returns ciphertext (string), initializationVector (string | nil). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Encrypt a Lua string and decrypt the returned ciphertext with the returned IV.

local key = crypt.generatekey()
local ciphertext, iv = crypt.encrypt("hello world", key)

local plaintext = crypt.decrypt(ciphertext, key, iv)

print(ciphertext)
print(iv)
print(plaintext)