Grav v1.14.0

Hash, Uuid and Ulid

import "std/data" (included in import "std") · namespace std.data

Hash functions turn data of any size into a short fingerprint: the same input always gives the same output, and different inputs almost never collide. Uuid makes random identifiers that are, in practice, unique everywhere.

FunctionGivesUse it for
Hash.sha256(s)64 hex digitsintegrity checks, fingerprints, content addressing
Hash.sha1(s), Hash.md5(s)40 / 32 hex digitscompatibility with formats that use them (both are broken for security)
Hash.crc32(s)a number below 2³²quick checksums, as in zip, gzip and PNG
Hash.fnv1a(s)a 64-bit numberfast hashing for tables and caches
Hash.randomToken(n)2n hex digitssession ids, password-reset tokens, nonces
Hash.hmacSha256(key, s)64 hex digitssigning cookies, tokens and webhooks
Hash.pbkdf2Sha256(pw, salt, iterations, n)2n hex digitspassword hashing (random salt, 600000+ iterations)
Hash.equals(a, b)a boolcomparing signatures and tokens in constant time (never ==)
Uuid.v4()xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxxdatabase keys, request ids
grav
import "std"

fn main() {
    print(Hash.sha256("abc"))
    print(Hash.md5("abc"))
    print(Hash.crc32("hello"))
    let fileData = Bytes.fromString("pretend these are file contents")
    print(Hash.sha256Bytes(fileData).length)

    let id = Uuid.v4()
    print(Uuid.isValid(id))
    print(id.length)
    print(Hash.randomToken(16).length)
}
Output
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
900150983cd24fb0d6963f7d28e17f72
907060870
64
true
36
32

Hashes are not encryption: they cannot be reversed. Plain SHA-256 is not suitable for storing passwords either, because it is too fast to compute; use a dedicated password-hashing algorithm for that. Uuid.v4 and Hash.randomToken use the operating system's random source, unlike Random, which is predictable by design.

Time-ordered ids

grav
import "std"

fn main() {
    let a = Uuid.v7()
    let b = Uuid.v7()
    print(a < b)                                   // made later, sorts later
    print(Uuid.timestampMs(a) <= Time.nowMs())
    let u = Ulid.generate()
    print(u.length)
    print(Ulid.isValid(u) && Ulid.timestampMs(u) > 0)
}
Output
true
true
26
true
  • Uuid.v7() (RFC 9562) starts with the unix milliseconds, so new rows land at the end of a primary-key index instead of anywhere in it, as with Uuid.v4(). Uuid.timestampMs(id) reads the time back (-1 for other versions).
  • Ulid.generate() gives a 26-character id in Crockford's Base32 (01JDQ8Z5J8A3T6V0K1R2M4N7PX): 48 bits of milliseconds, then 80 random bits. It is shorter than a UUID and sorts as text.
  • In order even within a millisecond. Both count up within one millisecond (UUID v7 in its 12-bit counter, ULID in its random part), across threads, and never go backwards when the clock does.
  • Speed. Ids and Hash.randomToken draw from a per-thread buffer of operating system randomness (one getentropy call per 256 bytes; a forked child starts a new one): about 0.75 µs for a UUID (v4 or v7) and 0.9 µs for a ULID.

API

class Hash

Hashes and checksums of text or bytes. The hash functions return lowercase hex.

Static members

  • static fn sha256(s: string) -> string — SHA-256 of the string's bytes, as 64 hex digits.
  • static fn sha256Bytes(b: Bytes) -> string — SHA-256 of raw bytes, as 64 hex digits.
  • static fn hmacSha256(key: string, message: string) -> string — HMAC-SHA256 of message under key (RFC 2104), as 64 hex digits: for signing cookies, tokens and webhooks.
  • static fn pbkdf2Sha256(password: string, salt: string, iterations: long, length: int) -> string — PBKDF2-HMAC-SHA256 (RFC 8018) of password with salt: length bytes (1..256) as 2*length hex digits. For password hashing use a random salt and at least 600000 iterations.
  • static fn equals(a: string, b: string) -> bool — Whether a and b are equal, comparing in time that depends only on their lengths (for signatures and tokens, never ==).
  • static fn sha1(s: string) -> string — SHA-1 of the string's bytes, as 40 hex digits (legacy: not for security).
  • static fn md5(s: string) -> string — MD5 of the string's bytes, as 32 hex digits (legacy: not for security).
  • static fn md5Bytes(b: Bytes) -> string — MD5 of raw bytes, as 32 hex digits (legacy: not for security).
  • static fn crc32(s: string) -> long — CRC-32 checksum (the one zip, gzip and PNG use), from 0 to 4294967295.
  • static fn crc32Bytes(b: Bytes) -> long — CRC-32 checksum of raw bytes.
  • static fn fnv1a(s: string) -> long — FNV-1a, a fast 64-bit hash for hash tables and fingerprints (not for security).
  • static fn randomToken(n: int) -> string — n random bytes from the operating system, as 2n hex digits: for session ids, tokens and nonces (n is at most 256).

class Uuid

Universally unique identifiers (RFC 4122).

Static members

  • static fn v4() -> string — A random (version 4) UUID such as "3f2b9c1e-8d4a-4f6b-9a2e-7c1d5e8f0a3b", from the operating system's random source.
  • static fn v7() -> string — A time-ordered (version 7) UUID: unix milliseconds first, so ids made later sort later (as text or bytes), and new rows land at the end of an index. Ids made in the same millisecond keep their order too.
  • static fn timestampMs(s: string) -> long — The unix milliseconds in a version 7 UUID, or -1 for any other.
  • static fn nil() -> string — The all-zero UUID.
  • static fn isValid(s: string) -> bool — Whether s has the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (hex digits, any case).

class Ulid

ULIDs: 26-character ids (Crockford Base32) that sort in the order made, "01JDQ8Z5J8A3T6V0K1R2M4N7PX": 48 bits of unix milliseconds, then 80 random bits (counting up within one millisecond).

Static members

  • static fn generate() -> string — A new ULID.
  • static fn timestampMs(s: string) -> long — The unix milliseconds in a ULID, or -1 when s is not one.
  • static fn isValid(s: string) -> bool — Whether s is a ULID (either case; O, I and L read as 0, 1 and 1).

Edit this page on GitHub