crypt.encrypt

Encrypts data using a specified algorithm and key.

Syntax

crypt.encrypt(data: string, key: string, iv?: string, mode?: string) -> string, string

Parameters

ParameterTypeDescription
datastringThe data to encrypt
keystringBase64-encoded 32-byte AES key
ivstring?Base64-encoded IV; generated when omitted
modestring?CBC, ECB, CTR, CFB, OFB, or GCM (default: CBC)

Returns

TypeDescription
stringBase64-encoded ciphertext
stringBase64-encoded IV used for encryption

Description

crypt.encrypt performs AES-256 encryption and returns both the ciphertext and the IV. CBC and ECB use PKCS#7 padding; GCM appends a 16-byte authentication tag before Base64 encoding.

Supported Algorithms

  • CBC (default)
  • ECB
  • CTR
  • CFB
  • OFB
  • GCM

Example

local key = crypt.generatekey()
local data = "Secret message"

-- Encrypt with default algorithm
local encrypted, iv = crypt.encrypt(data, key)
print("Encrypted:", encrypted)

-- Decrypt to verify
local decrypted = crypt.decrypt(encrypted, key, iv, "CBC")
print("Decrypted:", decrypted)

With Custom IV

local key = crypt.generatekey()
local iv = crypt.generatebytes(16)
local data = "Secret message"

local encrypted = crypt.encrypt(data, key, iv, "CBC")
local decrypted = crypt.decrypt(encrypted, key, iv, "CBC")