crypto

Token generation, checksums, and UUID-like identifiers in pure Bern.

import crypto
Note: These helpers are handy for IDs and checksums, but they are not a replacement for modern audited cryptography (AES, SHA-2, ed25519, …). Don't use them to protect secrets.

Random utilities

crypto_random_token(length) → string

A random alphanumeric token of the given length.

crypto_random_token(12)
-- Output: "a8Kx2Mq0Zb1p"   (example)
crypto_random_hex(byte_count) → string

Random hexadecimal text, two characters per requested byte.

crypto_random_hex(8)
-- Output: (16 hex chars, e.g. "3f0a9c12bb47de08")

Hashing & comparison

crypto_checksum32(text) → int

A 32-bit Adler-style checksum of the text.

crypto_checksum32("bern")
-- Output: (a 32-bit integer)
crypto_hash32_hex(text) → string

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)
crypto_secure_compare(a, b) → boolean

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

UUID-like IDs

crypto_uuid_v4_like() → string

A random identifier shaped like a UUID v4.

crypto_uuid_v4_like()
-- Output: "3f1a9c20-8b4e-4d77-9a2c-1e5f0b7c3d92"   (example)

Putting it together

A common pattern is issuing an ID together with a fingerprint, then verifying it later with a constant-time compare:

Issuing and verifying a signed token

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