crypt.encrypt Synchronous

Encrypt a byte string with AES and return the ciphertext together with the IV needed to read it later. GCM is a useful choice when you also want tampering with the saved value to be detected.

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

Parameters

Function parameters
ParameterTypeDescription
datastringPlaintext bytes, up to 16 MiB.
keystringBase64-encoded 32-byte key, such as the result of crypt.generatekey().
ivstring?Optional Base64 IV. Omit or pass nil to have Kawaii generate one for this encryption.
modestring?AES mode: CBC, ECB, CTR, CFB, OFB, or GCM. Names are case insensitive; CBC is the default.

Returns

(ciphertext: string, iv: string)

Two Base64 strings: ciphertext first, then the IV. Store both; only the key should remain secret.

Usage notes

Keep the key somewhere separate from the ciphertext. Save the returned IV with the ciphertext and pass the same mode to decrypt.

GCM also checks whether ciphertext was changed. The other listed modes do not provide that authentication on their own. CBC, CTR, CFB, and OFB use a 16-byte IV; GCM generates a 12-byte IV; ECB ignores the IV.

Example

Example
Luau
local key = crypt.generatekey()
local ciphertext, iv = crypt.encrypt("private note", key, nil, "GCM")
local recovered = crypt.decrypt(ciphertext, key, iv, "GCM")
assert(recovered == "private note")
Kawaii documentation