Hashing, keyed hashing, and cryptographically secure random bytes.
crypto.digest(algorithm, data, format?)→ A digest ofdata. The argumentalgorithmis a name like"SHA256"or"SHA512". The argumentformatis"hex"(default) or"raw", and any other value, such as a boolean, raisesOutput format must be "hex" or "raw".crypto.hmac(algorithm, key, data, format?)→ An HMAC, with the sameformatoptions.crypto.randomBytes(n)→ A string ofnrandom bytes.crypto.equals(a, b)→ Returnstrueif the two strings are equal, compared in constant time. Use this to verify a MAC, token, or any secret-derived value instead of==, which leaks bytes through timing.
Binary-safe, length-aware encoders and decoders. Decoding rejects malformed input with an error.
crypto.base64Encode(data)/crypto.base64Decode(text)→ Standard base64 with padding (+/,=).crypto.base64UrlEncode(data)/crypto.base64UrlDecode(text)→ URL-safe base64 (-_) with no padding. Decoding accepts either alphabet and optional padding.crypto.hexEncode(data)/crypto.hexDecode(text)→ Lowercase hex. Decoding accepts upper or lower case and rejects odd-length or non-hex input.
crypto.uuidV4()→ An RFC 4122 version 4 (random) UUID string, e.g."f47ac10b-58cc-4372-a567-0e02b2c3d479".crypto.uuidV7()→ An RFC 4122 version 7 (time-ordered) UUID string. The first 48 bits are a Unix-millisecond timestamp, so the values sort by creation time.
A password hash is slow by design, so both functions run on the task pool and answer a promise, and the loop keeps serving every other task and connection while the hash is computed.
crypto.hashPassword(password)→ A promise of a self-describing hash string of the formscrypt$N,r,p$salt$hash(salt and hash are URL-safe base64). Uses OpenSSL scrypt with a fresh random salt and interactive cost parameters (N=2^15,r=8,p=1). Store the returned string as-is.crypto.verifyPassword(password, hash)→ A promise oftruewhenpasswordmatches the storedhash, compared in constant time. It resolves tofalse(not an error) for a wrong password or a malformed hash string.
AES-256-GCM via OpenSSL. The key must be exactly 32 bytes (derive one with crypto.pbkdf2/crypto.hkdf or use crypto.randomBytes(32)).
crypto.encrypt(key, plaintext)→ A binary blob laid out asiv(12) || tag(16) || ciphertext. A fresh random IV is generated per call.crypto.decrypt(key, blob)→ The plaintext, or an error if the authentication tag does not verify (wrong key or tampered blob).crypto.rsaEncryptPublic(pemPublicKey, data)→ The inputdataencrypted with a PEM-encoded RSA public key using OAEP padding, returned as a binary blob.
Both derive raw key bytes. The argument algo is optional and defaults to "SHA256".
crypto.pbkdf2(password, salt, iterations, keyLen, algo?)→ A promise of akeyLen-byte key derived with PBKDF2-HMAC. The iterations make it as slow as the caller asks, so it runs on the task pool. A count or a length that is not positive raises at the call, while an unknown algorithm rejects the promise.crypto.hkdf(key, salt, info, keyLen, algo?)→ AkeyLen-byte key derived with HKDF (extract + expand).
There is no artificial input-size limit — Varn runs your own code on your own machine, so hashing or generating large data is allowed (bounded only by memory and the platform's integer limits). The digest, hmac, randomBytes, codec, and UUID helpers work in the browser build. The authenticated-encryption, password-hashing, key-derivation, and RSA functions are native-only and reject with "not available in this build" under WebAssembly.
-- Demonstrates the codec, uuid, password, encryption, and key derivation helpers.
local async = require("async")
local crypto = require("crypto")
-- Base64 and base64url codecs round-trip binary data.
local data = "varn \240\159\148\144 crypto"
print("base64: ", crypto.base64Encode(data))
print("base64url: ", crypto.base64UrlEncode(data))
print("hex: ", crypto.hexEncode(data))
assert(crypto.base64Decode(crypto.base64Encode(data)) == data)
assert(crypto.base64UrlDecode(crypto.base64UrlEncode(data)) == data)
assert(crypto.hexDecode(crypto.hexEncode(data)) == data)
-- Random identifiers, time-ordered with uuidV7.
print("uuid v4: ", crypto.uuidV4())
print("uuid v7: ", crypto.uuidV7())
-- Authenticated encryption with a 32-byte key, tamper-evident on decrypt.
local key = crypto.randomBytes(32)
local blob = crypto.encrypt(key, "attack at dawn")
print("ciphertext bytes:", #blob)
assert(crypto.decrypt(key, blob) == "attack at dawn")
local sub = crypto.hkdf(key, "", "session", 32, "SHA256")
print("hkdf key bytes: ", #sub)
async.run(function()
-- Password hashing produces a self-describing string you can store as-is.
local stored = crypto.hashPassword("hunter2"):await()
print("password: ", stored)
assert(crypto.verifyPassword("hunter2", stored):await())
assert(not crypto.verifyPassword("nope", stored):await())
-- Key derivation from a password.
local derived = crypto.pbkdf2("hunter2", crypto.randomBytes(16), 100000, 32, "SHA256"):await()
print("pbkdf2 key bytes:", #derived)
print("crypto extra example ok")
end)-- Checks the raw digest length for a fixed input string.
local crypto = require("crypto")
local raw = crypto.digest("SHA256", "raw-test", "raw")
assert(#raw == 32, "raw sha256 length")
print("crypto.digest raw ok, len=", #raw)-- Checks a short string against a known hex fingerprint.
local crypto = require("crypto")
local h = crypto.digest("SHA256", "varn", "hex")
assert(#h == 64, "sha256 hex length")
assert(h:match("^[0-9a-f]+$"), "expected lowercase hex")
print("crypto.digest SHA256 hex ok:", h:sub(1, 16), "...")-- Hashes a string with SHA-512 and prints the start of the hex digest.
local crypto = require("crypto")
local hex = crypto.digest("SHA512", "test", "hex")
assert(#hex == 128, "sha512 hex length")
print("crypto.digest SHA512 ok:", hex:sub(1, 16) .. "...")-- Verifies SHA-256 against known vectors for the empty and "abc" inputs.
local crypto = require("crypto")
assert(crypto.digest("SHA256", "", "hex")
== "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA256 empty string")
assert(crypto.digest("SHA256", "abc", "hex")
== "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "SHA256 abc")
print("crypto.digest SHA256 vectors ok (empty, abc)")-- Constant-time comparison for verifying a mac or token without leaking its bytes through timing.
local crypto = require("crypto")
local mac = crypto.hmac("SHA256", "server-secret", "session-42")
-- The caller presents a token verified in constant time, never with the == operator.
local presented = crypto.hmac("SHA256", "server-secret", "session-42")
assert(crypto.equals(mac, presented), "a matching token verifies")
assert(not crypto.equals(mac, "tampered"), "a wrong token is rejected")
print("crypto.equals ok")-- Produces a keyed hmac in raw binary form and checks its length.
local crypto = require("crypto")
local raw = crypto.hmac("SHA256", "secret-key", "message", "raw")
assert(#raw == 32, "raw hmac sha256 length")
print("crypto.hmac raw ok, len=", #raw)-- Verifies HMAC-SHA256 against RFC 4231 test case 1.
local crypto = require("crypto")
local key = string.rep("\x0b", 20)
local mac = crypto.hmac("SHA256", key, "Hi There", "hex")
assert(mac == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7", "HMAC-SHA256 RFC 4231 case 1")
print("crypto.hmac RFC 4231 vector ok")-- Asserts only on the length fields returned for random byte requests.
local crypto = require("crypto")
local b16 = crypto.randomBytes(16)
assert(#b16 == 16, "length")
local b32 = crypto.randomBytes(32)
assert(#b32 == 32, "length")
print("crypto.randomBytes ok")-- Shows randomBytes drawing a large requested size and rejecting a negative count.
local crypto = require("crypto")
local bytes = crypto.randomBytes(1024 * 1024)
assert(#bytes == 1024 * 1024, "draw the requested size")
local ok = pcall(crypto.randomBytes, -1)
assert(not ok, "a negative count is rejected")
print("crypto.randomBytes ok: len=", #bytes, "negative rejected")Hashes, HMAC, random bytes, base64/hex codecs, UUIDs, scrypt password hashing, AES-256-GCM, and PBKDF2/HKDF are all provided by OpenSSL.