crypt. encrypt Synchronous
Encrypt a byte string with AES and return both the Base64 ciphertext and its initialization vector. Use it when stored data needs confidentiality. The GCM example also authenticates the ciphertext; keep the key separate from the saved ciphertext and IV.
Luau
crypt.encrypt(
data: string,
key: string,
iv: string?,
mode: string?
) -> (ciphertext: string, iv: string)Parameters
| Parameter | Type | Description |
|---|---|---|
data | string | Plaintext bytes to encrypt, up to 16 MiB. |
key | string | Base64-encoded 32-byte key, such as the result of crypt.generatekey(). |
iv | string? | Optional Base64 IV. Omit it to generate a random IV for the selected mode. |
mode | string? | AES mode: CBC, ECB, CTR, CFB, OFB, or GCM. Defaults to CBC; names are case insensitive. |
Returns
(ciphertext: string, iv: string)Two Base64 strings: ciphertext and IV. Keep the IV alongside the ciphertext for decryption.
Usage notes
Keys decode to exactly 32 bytes. CBC, CTR, CFB, and OFB use a 16-byte IV; a 32-byte IV is truncated for compatibility. GCM generates a 12-byte IV and accepts supplied IVs of at least 12 bytes. ECB ignores the IV.
Use the same mode for encryption and decryption. Ciphertext and IV are Base64 strings; plaintext is raw bytes.
Example
Luau
local key = crypt.generatekey()
local encrypted, iv = crypt.encrypt("private example note", key, nil, "GCM")
local restored = crypt.decrypt(encrypted, key, iv, "GCM")
print(restored) -- private example note