Token generation, checksums, and UUID-like identifiers in pure Bern.
import crypto
A random alphanumeric token of the given length.
crypto_random_token(12) -- Output: "a8Kx2Mq0Zb1p" (example)
Random hexadecimal text, two characters per requested byte.
crypto_random_hex(8) -- Output: (16 hex chars, e.g. "3f0a9c12bb47de08")
A 32-bit Adler-style checksum of the text.
crypto_checksum32("bern")
-- Output: (a 32-bit integer)
The checksum rendered as an 8-character hex string - useful as a short content fingerprint.
crypto_hash32_hex("bern")
-- Output: (8 hex chars)
crypto_hash32_hex("bern") == crypto_hash32_hex("bern")
-- Output: true (same input → same hash)
Compare two strings with a fixed-length scan to reduce timing leakage.
crypto_secure_compare("token123", "token123")
-- Output: true
crypto_secure_compare("token123", "token124")
-- Output: false
A random identifier shaped like a UUID v4.
crypto_uuid_v4_like() -- Output: "3f1a9c20-8b4e-4d77-9a2c-1e5f0b7c3d92" (example)
A common pattern is issuing an ID together with a fingerprint, then verifying it later with a constant-time compare:
import crypto -- issue id = crypto_uuid_v4_like() token = crypto_random_token(16) sig = crypto_hash32_hex(id + token) -- ...later, verify a presented (id, token) pair def verify(id, token, sig) -> crypto_secure_compare(crypto_hash32_hex(id + token), sig) verify(id, token, sig) -- Output: true verify(id, "wrong-token", sig) -- Output: false