Cryptography
Encode, encrypt, hash and generate random data with the crypt library.
The crypt library works on strings, and binary data is fine: Luau strings hold arbitrary bytes. Keys, IVs and ciphertext are base64-encoded, so they're safe to store with writefile or send over HTTP.
Encoding
crypt.base64encode
since 1.0.0crypt.base64encode(data: string): stringEncodes data as base64.
Also available as base64_encode and crypt.base64.encode.
Parameters
datastring- Any string, including binary data.
Returns
stringThe base64 encoding.
Example
crypt.base64decode
since 1.0.0crypt.base64decode(data: string): stringDecodes a base64 string. Errors on invalid input.
Also available as base64_decode and crypt.base64.decode.
Parameters
datastring- A base64 string.
Returns
stringThe decoded bytes.
Example
Encryption
crypt.encrypt
since 1.0.0crypt.encrypt(data: string, key: string, iv: string?, mode: string?): (string, string)Encrypts data with AES-256. Returns the base64-encoded ciphertext and the IV that was used, which is random unless you pass one.
Parameters
datastring- The plaintext.
keystring- A base64-encoded 32-byte key, such as one from
crypt.generatekey(). ivstring?- Optional.A base64-encoded 16-byte IV. Generated for you when omitted.
modestring?- Optional.
"CBC","CTR","CFB","OFB","ECB"or"GCM". Default"CBC".
Returns
(string, string)The ciphertext and the IV, both base64.
Example
crypt.decrypt
since 1.0.0crypt.decrypt(data: string, key: string, iv: string, mode: string): stringDecrypts base64 ciphertext produced by crypt.encrypt. The key, IV and mode must match the ones used to encrypt. Unlike crypt.encrypt, the mode has no default here.
Parameters
datastring- The base64 ciphertext.
keystring- The base64 key used to encrypt.
ivstring- The base64 IV returned by
crypt.encrypt. modestring- The mode used to encrypt, such as
"CBC".
Returns
stringThe plaintext.
Example
Hashing
crypt.hash
since 1.0.0crypt.hash(data: string, algorithm: string?): stringReturns the hash of data as a lowercase hex string.
Parameters
datastring- The data to hash.
algorithmstring?- Optional.
"md5","sha1","sha224","sha256","sha384","sha512","sha3-224","sha3-256","sha3-384"or"sha3-512". Default"sha256".
Returns
stringThe hex digest.
Example
Random data
crypt.generatekey
since 1.0.0crypt.generatekey(): stringReturns a random 256-bit key, base64-encoded, from a cryptographically secure source.
Returns
stringA base64 key for crypt.encrypt.
Example
crypt.generatebytes
since 1.0.0crypt.generatebytes(size: number?): stringReturns size cryptographically secure random bytes, base64-encoded.
Parameters
sizenumber?- Optional.How many bytes to generate, up to 1024. Default
16.
Returns
stringThe bytes, base64-encoded.
Example
Written for Lynx 0.0.0
Something unclear? Tell us on Discord