1 API

The following is the list of modules provided by this library. The stylesheet and the script that present this chapter in a browser are written beside it, as dokgen.css and dokgen.js; the manual says how a build points at them.


1.1 (bewaking bewaking)

Tokens, sealed objects and the envelope they travel in.

An envelope is sealed twice: the plaintext is encrypted under the caller’s encryption key, the Base64 payload that comes out is garbled, and the garbled text is sealed again under a key derived from the signing key. The outer layer’s cipher tag is the integrity check, and it authenticates the header – the version, the key id and the two timestamps – as associated data, so a header that was altered is a body that does not open.

Mermaid diagram, as source:

flowchart LR
  plaintext["plaintext"] --> inner["AES-256-CBC<br/>encryption key"]
  inner --> garble["string-garble"]
  header["header: version,<br/>key id, timestamps"] --> outer
  garble --> outer["AES-256-GCM<br/>signing key"]
  outer --> envelope["BWK3 envelope:<br/>header and body"]

‘open-envelope’ walks the same path backwards, and refuses a body whose tag does not verify before it looks at the expiry it was told to enforce.

1.1.1 Overview

1.1.2 Procedures

Procedure: argon2id-available?

Return #t when the loaded libgcrypt provides Argon2 (1.11 or newer).

Procedure: base16-decode value

Decode the hexadecimal string value into a string. Upper and lower case digits are both accepted. Raises an error when the input has an odd number of digits or contains a non-hexadecimal character.

Procedure: base16-encode value

Return the lowercase hexadecimal encoding of the string value, one byte per two digits.

Procedure: decrypt-object KEY: #:object #:encryption-key #:signing-key #:keyring #:enforce-expiry? #:max-age-seconds #:now

Safely reopen a string produced by ‘encrypt-object‘. Wraps ‘unsafe-decrypt-object‘, catching errors and returning #f instead of raising.

See ‘unsafe-decrypt-object‘ for the keyword arguments.

Procedure: decrypt-payload payload k

Decrypt a payload previously produced by ‘encrypt-payload‘, by openssl enc -aes256 -pbkdf2 -a -A, or by any other implementation of that format. Which key derivation to use is read from the payload itself, so no options are needed to open data sealed with either KDF. Raises an error when the input is not a sealed payload or when its padding is invalid, which is how a wrong key is reported.

#:args payload: The Base64-encoded, AES256-encrypted string to decrypt. k: The decryption key (a string) that was used to encrypt the payload.

#:returns The original, decrypted data as a string.

#:example (decrypt-payload "U2FsdGVkX1+..." "mysecretkey")

Procedure: decrypt-token KEY: #:token #:encryption-key #:signing-key #:keyring #:enforce-expiry? #:max-age-seconds #:now

Safely attempts to decrypt a given token. This function acts as a wrapper around ‘unsafe-decrypt-token‘, catching any errors that occur during the decryption process.

Args: token: The token string to be decrypted. encryption-key: The key used for encryption. signing-key: The key whose derived AES-256-GCM layer authenticates the envelope. keyring: (Optional) alist of key-id -> key entry for key rotation. enforce-expiry?: (Optional) when #t (the default) expired envelopes are rejected. max-age-seconds: (Optional) reject envelopes sealed longer ago than this.

Returns: The decrypted token payload if successful, otherwise ‘#f‘ (false) and prints an error message to the console.

Procedure: encrypt-object KEY: #:payload #:encryption-key #:signing-key #:keyring #:key-id #:ttl-seconds #:expires-at #:kdf #:created-at #:random-source

Safely seal an arbitrary Scheme datum. Wraps ‘unsafe-encrypt-object‘, catching errors and returning #f instead of raising.

See ‘unsafe-encrypt-object‘ for the keyword arguments.

Procedure: encrypt-payload payload k KEY: #:kdf #:salt

Encrypt payload with AES-256-CBC under the passphrase k, deriving the AES key and IV with kdf (see kdf-spec in (bewaking crypto)). The result records which derivation was used, so it can always be opened again without being told.

The output uses exactly the layout of openssl enc -aes256 -pbkdf2 -a -A -k KEY, so data produced by either implementation can be read by the other:

- an 8-byte random salt, stored in an OpenSSL Salted__ header; - a 32-byte key and a 16-byte IV derived from the passphrase and that salt with PBKDF2-HMAC-SHA256 over 10000 iterations; - AES-256-CBC with PKCS#7 padding, Base64-encoded on a single line.

The work happens inside this process; nothing is passed to a shell.

#:args payload: The string to encrypt. k: The encryption key (a string) to use.

#:returns A Base64 string such as "U2FsdGVkX1+...".

#:key kdf: the key-derivation specification; 'pbkdf2 (the default) keeps the OpenSSL-compatible layout, 'argon2id selects Argon2id with its default parameters. #:key salt: the salt bytes to use (8 for PBKDF2, 16 for Argon2id); the default is fresh random bytes. Supplying one is how a caller reproduces a sealed blob exactly, for a stored test vector or a cross-implementation check.

#:example (encrypt-payload "mysecretdata" "mysecretkey") (encrypt-payload "mysecretdata" "mysecretkey" #:kdf ’argon2id)

Procedure: envelope-expired? KEY: #:sealed #:now

Return #t when sealed is an envelope carrying an expires-at in the past relative to now, and #f otherwise — including envelopes with no expiry and non-envelope values.

This is an unauthenticated audit helper that reads the header only. Use ‘open-envelope‘, which verifies the cipher tag, to enforce expiry during decryption.

Procedure: envelope-metadata KEY: #:sealed

Return an alist of envelope metadata without needing any key: version, key-id, created-at and expires-at.

expires-at is #f when the data never expires. Returns #f when sealed is not a well-formed envelope.

Reading this needs no key, which is what makes it useful for auditing; the metadata is authenticated by the envelope’s cipher tag, so ‘open-envelope‘ will not act on it before that protection has been accepted. Treat this function’s result as a *claim* to log, never as a decision: only ‘open-envelope‘ can say whether the envelope is genuine.

Procedure: generate-token KEY: #:encryption-key #:signing-key #:keyring #:key-id #:get-owner-details #:token-validity-seconds #:ttl-seconds #:expires-at #:kdf #:now #:token-id #:random-source

Safely attempts to generate a new token. This function wraps ‘unsafe-generate-token‘ to gracefully handle any potential errors during token creation.

Args: encryption-key: The key to be used for encrypting the token’s payload. signing-key: The key to be used for signing the token. keyring: (Optional) alist of key-id -> key entry for key rotation. key-id: (Optional) label embedded in the envelope (default "default"). get-owner-details: A thunk that returns a list of details about the token’s owner. token-validity-seconds: (Optional) The payload validity duration in seconds. ttl-seconds: (Optional) Envelope lifetime in seconds; seals an expiry into the token. expires-at: (Optional) Explicit Unix timestamp for the envelope expiry. kdf: (Optional) Key-derivation specification; ’pbkdf2 (the default) or ’argon2id, or an alist of parameters. Recorded in the token itself.

Returns: A newly generated token string if successful, otherwise ‘#f‘ (false) and prints an error message to the console.

Procedure: has-needed-permissions? KEY: #:needed #:present

Check if needed permissions are a subset of the present (existing) permissions.

Procedure: is-token-expired? KEY: #:token

Return #t when the token’s token-expires-at timestamp is in the past, and #f while the token is still valid. Raises an error when the payload is missing a well-formed token-expires-at field.

#:key token: A decrypted token payload (association list).

#:example (is-token-expired? #:token (decrypt-token #:token t #:encryption-key k1 #:signing-key k2))

Procedure: open-envelope KEY: #:sealed #:encryption-key #:signing-key #:keyring #:enforce-expiry? #:now #:max-age-seconds

Open a sealed envelope and return its plaintext string.

The envelope is opened with AES-256-GCM, whose tag also covers the rotation metadata (key id, created-at, expires-at): no plaintext is returned unless the tag verifies, so the metadata cannot be read as authentic before the cipher has accepted it, and tampering is refused rather than decrypted and then distrusted.

A refusal is deliberately unspecific. An unknown key id, a retired key, a key that is not active yet, a wrong key and altered data all raise the same error, and the attempt is made with a placeholder key rather than abandoned early, so the work done is comparable too. See ‘envelope-refusal-message’. Expiry is the one distinguishable case, because it is only reached once the tag has proved the envelope genuine, and an operator needs to know that live data merely went stale.

#:key enforce-expiry?: when #t (the default) an envelope whose expires-at is in the past is rejected. #:key now: current Unix timestamp, for deterministic checks. #:key max-age-seconds: optional; reject envelopes created longer ago than this. #:key keyring: optional alist of key id to key entry; the entry’s not-before / not-after window is enforced.

Anything that is not a well-formed BWK3 envelope — an envelope of an earlier format version, a pre-versioning bare Base16 token, or arbitrary text — is refused.

Procedure: seal-envelope KEY: #:plaintext #:encryption-key #:signing-key #:key-id #:created-at #:expires-at #:ttl-seconds #:kdf #:random-source

Seal a plaintext string into a versioned, authenticated envelope.

The output is BWK3.<key-id>.<created-at>.<expires-at>.<body>, where the body is a sealed payload whose authenticity comes from AES-256-GCM keyed by the signing key. An encryption key and a signing key are all that is required: there is no MAC key, because the cipher tag is the integrity check.

#:key created-at: Unix timestamp to record (default: now). #:key expires-at: Unix timestamp after which the data must not be opened. #:key ttl-seconds: convenience; sets expires-at to created-at + ttl-seconds. Give at most one of expires-at / ttl-seconds. #:key kdf: how the AES keys are derived from the two keys, either a symbol such as 'pbkdf2 (the default) or 'argon2id, or an alist of parameters as accepted by kdf-spec in (bewaking crypto). The choice is recorded in the sealed body, so opening needs no matching option. #:key random-source: a procedure taking a byte count and returning that many bytes; defaults to ‘random-bytes’, libgcrypt’s CSPRNG. It supplies the inner salt, the GCM salt and the nonce. Override it only to reproduce an envelope exactly (in a test vector, or a compatibility check): a constant source reuses nonces, which is unsafe for real data.

#:example (seal-envelope #:plaintext some-plaintext #:encryption-key k1 #:signing-key k2 #:ttl-seconds (* 24 3600)) (seal-envelope #:plaintext some-plaintext #:encryption-key k1 #:signing-key k2 #:kdf ’argon2id)

Procedure: sealed-envelope? sealed

Return #t when sealed is a bewaking envelope of any readable format version.

Procedure: string-garble s

Garbles a string by splitting it into two halves, reversing each half, and then concatenating the reversed second half with the reversed first half. If the string has an odd length, the first half will be shorter by one character.

#:args s: The input string to garble.

#:return A new string that is the garbled version of the input string.

Example: (string-garble "abcdefg") ; Returns "gfedcba" (string-garble "hello world") ; Returns "dlrow olleh"

Procedure: string-ungarble s

Ungarbeles a string that was previously garbled by the ‘string-garble‘ function. It reconstructs the original string by reversing the process of ‘string-garble‘.

Args: s: The garbled string to ungarble.

Returns: The original string before it was garbled.

Example: (string-ungarble "gfedcba") ; Returns "abcdefg" (string-ungarble "dlrow olleh") ; Returns "hello world"

Procedure: token-payload-valid? payload

Verify the validity of a token payload, by doing checks on every field, and returning either #t or #f representing validity status.

Procedure: token-remaining-seconds KEY: #:token

Return the number of seconds left before the token expires.

The value is positive while the token is still valid, zero at the exact expiry instant, and negative once the token has expired. Raises an error when token-expires-at is missing or is not a number.

#:key token: A decrypted token payload (association list).

Procedure: token-valid? KEY: #:token

Return #t when the decrypted token payload is structurally valid (‘token-payload-valid?‘) and has not expired yet (‘is-token-expired?‘).

#:key token: A decrypted token payload (association list).

Procedure: unsafe-decrypt-object KEY: #:object #:encryption-key #:signing-key #:keyring #:enforce-expiry? #:max-age-seconds #:now

Reopen a string produced by ‘unsafe-encrypt-object‘, returning the original Scheme datum. The envelope’s authentication tag is checked as it is opened, so tampering is reported explicitly and no plaintext exists before that check. Raises an error if the object cannot be decrypted.

#:key object: The sealed string to decrypt. #:key encryption-key: The inner AES-256 key (string). #:key signing-key: The key whose derived AES-256-GCM layer authenticates the envelope. #:key keyring: Optional alist of key-id -> key entry. When supplied, keys are selected using the sealed data’s own key id. #:key enforce-expiry?: When #t (the default), an object whose envelope expiry has passed is rejected. #:key max-age-seconds: Optional rotation policy; reject objects sealed longer ago than this. #:key now: Current Unix timestamp, for deterministic checks. #:returns: The original Scheme datum.

Procedure: unsafe-decrypt-token KEY: #:token #:encryption-key #:signing-key #:keyring #:enforce-expiry? #:max-age-seconds #:now

Decodes and validates a secure token created by ‘generate-token‘.

Tokens carry a version tag, a key id and an authentication tag inside the sealed body. The tag is checked *while* the token is opened, so tampering is reported explicitly and no plaintext exists before authenticity is established. Anything that is not a current-version envelope is refused.

All cryptography is performed in this process (see the module ‘(bewaking crypto)‘); no external command-line tools are involved.

#:key token: The token string to decrypt. #:key encryption-key: The key used for the inner AES-256 encryption. #:key signing-key: The key whose derived AES-256-GCM layer authenticates the envelope. #:key keyring: Optional alist of key-id -> key entry. When supplied, keys are selected using the token’s own key id. #:key enforce-expiry?: When #t (the default), an envelope whose expiry has passed is rejected. #:key max-age-seconds: Optional rotation policy; reject envelopes sealed longer ago than this. #:key now: Current Unix timestamp, for deterministic checks.

#:returns: A parsed association list representing the token’s payload if the token is valid and successfully decoded. Otherwise, it raises an error.

Procedure: unsafe-encrypt-object KEY: #:payload #:encryption-key #:signing-key #:keyring #:key-id #:ttl-seconds #:expires-at #:kdf #:created-at #:random-source

Seal an arbitrary Scheme datum (not just a token payload) into a portable, versioned, authenticated string. Any value that ‘write‘ can serialize is supported: alists, lists, vectors, numbers, strings, booleans, etc.

#:key payload: The Scheme datum to protect. #:key encryption-key: The inner AES-256 key (string). Required unless a keyring is supplied. #:key signing-key: The key (string) whose derived AES-256-GCM layer authenticates the envelope. #:key keyring: Optional alist of key-id -> key entry for key rotation. #:key key-id: Key identifier embedded in the envelope (default "default"). #:key ttl-seconds: Optional envelope lifetime in seconds. The envelope then records an expiry and refuses to reopen afterwards. #:key expires-at: Optional Unix timestamp for the envelope expiry; mutually exclusive with ttl-seconds. #:key kdf: How the AES keys are derived from the two keys: ’pbkdf2 (the default) or ’argon2id, or an alist of parameters as accepted by ‘kdf-spec‘. The choice travels inside the sealed body. #:returns: A versioned, authenticated envelope string.

#:example (unsafe-encrypt-object #:payload ’((user . "joe") (role . admin)) #:encryption-key "..." #:signing-key "...")

Procedure: unsafe-generate-token KEY: #:encryption-key #:signing-key #:keyring #:key-id #:get-owner-details #:token-validity-seconds #:ttl-seconds #:expires-at #:kdf #:now #:token-id #:random-source

Generates a secure, versioned, authenticated token.

#:key encryption-key: The secret key (string) used for AES-256 encryption. #:key signing-key: The signing key (string) used to derive the key of the AES-256-GCM layer that authenticates the token. #:key keyring: Optional alist of key-id -> key entry used to select keys instead of the explicit keys above. #:key key-id: Key identifier embedded in the envelope (default "default"). Enables key rotation. #:key get-owner-details: A thunk that returns an the owner’s details. #:key token-validity-seconds: The token’s payload lifetime in seconds. #:key ttl-seconds: Optional envelope lifetime in seconds. When given, the sealed envelope records an expiry and ‘decrypt-token‘ refuses to open it afterwards (default: no expiry). #:key expires-at: Optional Unix timestamp for the envelope expiry; mutually exclusive with ttl-seconds. #:key kdf: How the AES keys are derived from the two keys. Use 'argon2id for a memory-hard derivation; the default is PBKDF2, which is what older tokens use. #:key now: Unix timestamp to record as the creation time and to compute the expiry from (default: the wall clock). Supplying it makes a token reproducible. #:key token-id: The UUID to record as the token id (default: a fresh random one). Supplying it makes a token reproducible. #:key random-source: A procedure taking a byte count and returning that many bytes; defaults to the CSPRNG. Override it only together with ’now’ and ’token-id’, and only to reproduce a token exactly: a constant source reuses nonces, which is unsafe for real data. #:returns: A versioned, authenticated token string.

1.1.3 Variables

Variable: default-kdf
pbkdf2
Variable: default-key-id
"default"
Variable: readable-seal-format-versions
("BWK3")
Variable: seal-format-version
"BWK3"

1.2 (bewaking cli)

1.2.1 Overview

  • run — Run the bewaking command-line interface with args (a list of strings,
  • usage — A variable.

1.2.2 Procedures

Procedure: run args

Run the bewaking command-line interface with args (a list of strings, without the program name). Returns the process exit code: 0 on success and 1 on any error or usage problem.

1.2.3 Variables

Variable: usage
"bewaking — encrypted tokens, sealed objects and password tools\n\nUsage:\n  bewaking token generate   [options]\n  bewaking token decrypt    [options]\n  bewaking token inspect    [options]\n  bewaking object encrypt   [options]\n  bewaking object decrypt   [options]\n  bewaking password strength [PASSWORD]\n  bewaking password generate [options]\n  bewaking password hash     [options] [PASSWORD]\n  bewaking password verify   HASH [PASSWORD]\n  bewaking help\n\nKeys (required for token/object commands, unless --keyring is given):\n  --encryption-key KEY          inner AES-256 key (1st seal)\n  --encryption-key-file FILE    read the inner key from FILE\n  --signing-key KEY             outer AES-256 key (2nd seal)\n  --signing-key-file FILE       read the outer key from FILE\n  --keyring FILE                Scheme alist of key-id -> keys, for rotation\n  --key-id LABEL                key id embedded when sealing (default \"default\")\n  Environment fallbacks: BEWAKING_ENCRYPTION_KEY, BEWAKING_SIGNING_KEY\n\nRotation metadata (recorded in the sealed header and covered by the cipher tag):\n  --ttl-seconds N               seal data that expires N seconds from now\n  --expires-at TS               seal data that expires at an absolute Unix time\n  --max-age-seconds N           refuse data sealed longer ago than N seconds\n  --allow-expired               open expired data anyway (audit/recovery only)\n\nKey derivation (sealing only; opening reads it back from the data itself):\n  --kdf NAME                    pbkdf2 (default) or argon2id\n  --kdf-memory-kib N            Argon2id memory cost in KiB (default 65536)\n  --kdf-iterations N            Argon2id passes (default 3)\n  --kdf-parallelism N           Argon2id lanes (default 1)\n  Argon2id requires libgcrypt 1.11 or newer. The cost is per AES layer and a\n  token has two, so sealing and opening each derive twice: 64 MiB with 3\n  passes is around 90 ms per derivation, 8 MiB with 1 pass around 3 ms.\n  PBKDF2 takes no parameters, because the OpenSSL-compatible format it\n  produces has nowhere to record them.\n\nA keyring file has the shape (not-before/not-after are optional rotation\nwindows; using a key outside its window is refused):\n  ((\"2026a\" (encryption-key . \"e1\") (signing-key . \"s1\"))\n   (\"2025b\" (encryption-key . \"e0\") (signing-key . \"s0\")\n            (not-after . 1790000000)))\n\ntoken generate:\n  --owner-details FILE          owner alist read from FILE (alternative below)\n  --owner-id ID                 owner id (required unless --owner-details)\n  --owner-email EMAIL           owner email\n  --owner-name NAME             owner name\n  --permissions a,b,c           comma-separated permission symbols\n  --validity-seconds N          token lifetime (default 604800)\n\ntoken decrypt:\n  --token TOKEN                 token string\n  --token-file FILE             read the token from FILE\n\ntoken inspect:\n  --token TOKEN | --token-file FILE\n                                print the envelope metadata (version, key id,\n                                created-at, expiry) without needing any key\n\nobject encrypt / object decrypt:\n  --input FILE                  read the payload/sealed string from FILE\n                                (default: standard input)\n\npassword strength:\n  PASSWORD (positional) or one line on standard input\n\npassword generate:\n  --length N                    password length (default 24)\n  --no-symbols                  exclude symbol characters\n\npassword hash:\n  PASSWORD (positional) or one line on standard input\n  --kdf-memory-kib N            Argon2id memory cost in KiB (default 65536)\n  --kdf-iterations N            Argon2id passes (default 3)\n  --kdf-parallelism N           Argon2id lanes (default 1)\n\npassword verify:\n  HASH                          the PHC string printed by `password hash`\n  PASSWORD (positional) or one line on standard input\n  Exits 1 when the password does not match, so a shell can branch on it.\n\nExamples:\n  bewaking token generate --owner-id 42 --owner-name Joe \\\n      --permissions read,write --encryption-key \"$K1\" --signing-key \"$K2\"\n  bewaking token decrypt --token \"$TOKEN\" \\\n      --encryption-key \"$K1\" --signing-key \"$K2\"\n  echo '((name . Joe) (score . 7))' | bewaking object encrypt \\\n      --encryption-key \"$K1\" --signing-key \"$K2\"\n  bewaking token generate --owner-id 42 --kdf argon2id \\\n      --kdf-memory-kib 8192 --encryption-key \"$K1\" --signing-key \"$K2\"\n  bewaking password generate --length 32\n  bewaking password hash 'correct horse battery staple'\n  bewaking password verify '$argon2id$v=19$...' 'correct horse battery staple'\n"

1.3 (bewaking crypto)

1.3.1 Overview

1.3.2 Procedures

Procedure: argon2id-available?

Return #t when the loaded libgcrypt provides Argon2 (1.11 or newer).

Procedure: argon2id-derive password salt length KEY: #:memory-kib #:iterations #:parallelism #:secret #:associated-data

Derive length bytes from the string password and bytevector salt with Argon2id, version 1.3 (19), as specified by RFC 9106.

#:key memory-kib: memory cost, in kibibytes (default 65536, i.e. 64 MiB). #:key iterations: time cost, i.e. number of passes (default 3). #:key parallelism: number of lanes (default 1). #:key secret: optional bytevector used as Argon2’s secret value, called K in RFC 9106. Bewaking’s own sealing does not use it, so that the sealed data can be opened with the passphrase alone; it is accepted because a caller with a second key may want it. #:key associated-data: optional bytevector used as Argon2’s associated data, called X in RFC 9106.

Raises an error when libgcrypt has no Argon2 support, when the parameters are out of range, or when the platform’s ‘unsigned long’ does not match the pointer width the parameter array is built from.

#:example ;; The Argon2id vector of RFC 9106, Section 5.3. (argon2id-derive (make-string 32 (integer->char 1)) (make-bytevector 16 2) 32 #:memory-kib 32 #:iterations 3 #:parallelism 4 #:secret (make-bytevector 8 3) #:associated-data (make-bytevector 12 4))

Procedure: base16->bytes value

Decode the hexadecimal string value into a bytevector. Upper and lower case digits are both accepted. Raises an error when the input has an odd number of digits or contains a non-hexadecimal character.

Unlike ‘base16-decode‘ this returns the raw bytes, so it can read hexadecimal that stands for binary data rather than for text.

Procedure: base16-decode value

Decode the hexadecimal string value into a string. Upper and lower case digits are both accepted. Raises an error when the input has an odd number of digits or contains a non-hexadecimal character.

Procedure: base16-encode value

Return the lowercase hexadecimal encoding of the string value, one byte per two digits.

Procedure: base64->bytes value

Decode the Base64 string value into a bytevector. Whitespace is ignored, up to two trailing padding characters are accepted, and anything else raises an error.

Procedure: base64-decode value

Decode the Base64 string value into a string. Whitespace is ignored and anything that is not Base64 raises an error.

Procedure: base64-encode value

Return the standard, padded, single-line Base64 encoding of the string value.

Procedure: bytes->base16 bytes

Return the lowercase hexadecimal encoding of bytes, one byte per two digits.

Procedure: bytes->base64 bytes

Return the standard, padded, single-line Base64 encoding of bytes.

Procedure: call-with-error-handler thunk handler

Call thunk, passing an ordinary error to handler as a key and args list.

An asynchronous interrupt is not an ordinary error: a SIGINT arrives as ~(throw ’signal ...)~, and a ~(quit)~ or ~(exit)~ as ~’quit~. Those are rethrown untouched, so wrapping a long derivation in this helper does not make Ctrl-C stop working. Everything else — what ~error~ raises — is handed to handler, which is why the safe ~decrypt-token~-style wrappers can turn any failure into a value without swallowing the operator’s interrupt.

Procedure: condition-message key args

Best-effort human-readable text for an exception caught as key with args, for diagnostics that a person has to read.

Guile reports an ~error~ through a formatting list whose leading element is the report port, and versions differ on whether that list arrives flat in args or nested inside it, so both shapes are accepted. Falls back to a plain string argument, then to the exception key, so a diagnostic is never lost.

Procedure: constant-time-equal? left right

Return #t when the string or bytevector left holds the same bytes as the string or bytevector right.

Every byte of the shorter-length comparison is examined, and the differences are accumulated before the answer is decided, so the running time depends on the length only: an attacker who can time the check learns nothing about how many leading bytes were right. Lengths that differ answer #f at once, which is the one thing this cannot hide — compare fixed-length material, such as a PBKDF2/Argon2 digest, rather than a variable-length password.

Procedure: derive-key-material kdf password salt length

Derive length bytes from the string password and the bytevector salt, with the key-derivation function described by kdf (see ‘kdf-spec’). Raises an error for an unknown derivation or for parameters the chosen derivation cannot use.

Procedure: gcm-decrypt sealed key KEY: #:associated-data

Open a Base16 string produced by ‘gcm-encrypt’ under the string key, and return the plaintext bytevector.

Which key derivation to use, and with which parameters, is read from the sealed payload itself, so nothing has to be configured to open it. The recorded parameters are checked before a key is derived from them. Raises an error when the payload is malformed or truncated, when its key derivation is unknown, or when the authentication tag does not match — as happens with a wrong key, altered ciphertext, or associated data that is not the same as when the payload was sealed.

Procedure: gcm-encrypt plaintext key KEY: #:kdf #:salt #:nonce #:associated-data

Seal the bytevector plaintext under the string key, deriving the 32-byte AES-256-GCM key with kdf, and return a Base16 string that records which derivation was used and with which parameters.

#:key kdf: the key-derivation specification; see ‘kdf-spec’. #:key salt: the 16 salt bytes to use; defaults to fresh random bytes. #:key nonce: the 12 nonce bytes to use; defaults to fresh random bytes. It must never repeat under the same key, which is why it defaults to a fresh random value. #:key associated-data: optional bytevector that is authenticated together with the ciphertext but stored by the caller. Opening requires the identical bytes.

Procedure: hmac-sha256-hex key message

Return the HMAC-SHA256 of the string message under the string key, as a lowercase hexadecimal string.

Procedure: kdf-decrypt sealed key

Decrypt a Base64 string produced by ‘kdf-encrypt’ (or, for the PBKDF2 layout, by openssl enc -aes256 -pbkdf2 -a -A) under the string key, returning the original plaintext string.

Which key derivation to use, and with which parameters, is read from the sealed payload itself, so nothing has to be configured to open old data. Raises an error when the payload is not sealed, when its parameters are out of range, or when the padding is invalid — as happens with a wrong key.

Procedure: kdf-encrypt plaintext key KEY: #:kdf #:salt

Encrypt the string plaintext under the string key, deriving the AES-256 key and IV with kdf, and return a Base64 string that records which derivation was used.

#:key kdf: the key-derivation specification; see ‘kdf-spec’. Defaults to PBKDF2, which produces the OpenSSL-compatible layout. #:key salt: the salt bytes to use, 8 for PBKDF2 and 16 for Argon2id; defaults to fresh random bytes.

Procedure: kdf-name kdf

Return the name of the key-derivation function named by kdf.

Procedure: kdf-salt-length kdf

Return the salt length, in bytes, that the derivation named by kdf uses inside a sealed payload: 8 for the OpenSSL-compatible PBKDF2 layout, 16 for Argon2id. Callers that supply their own salt need this to size it.

Procedure: kdf-spec kdf

Normalize a key-derivation specification into a complete alist.

kdf may be the symbol ~pbkdf2~ (the default), the symbol ~argon2id~, or an alist whose ~kdf~ entry names the function and whose remaining entries are its parameters, as in ~’((kdf . argon2id) (memory-kib . 262144))~. Missing parameters are filled in with the defaults, so the result can be handed straight to ‘kdf-encrypt’. Raises an error for an unknown KDF or an out-of-range parameter.

Procedure: openssl-decrypt ciphertext key

Decrypt a Base64 string produced by ‘openssl-encrypt’ (or by openssl enc -aes256 -pbkdf2 -a -A) under the string key, and return the original plaintext string. Raises an error when the input is not in that format or when the padding is invalid, as happens with a wrong key.

Procedure: openssl-encrypt plaintext key KEY: #:salt

Encrypt the string plaintext under the string key and return the result as a Base64 string, in the exact format produced by openssl enc -aes256 -pbkdf2 -a -A -k KEY: an 8-byte random salt in a Salted__ header followed by the AES-256-CBC ciphertext.

#:key salt: the 8 salt bytes to use; defaults to fresh random bytes.

Procedure: pbkdf2-sha256 password salt length KEY: #:iterations

Derive length bytes from the string password and bytevector salt using PBKDF2-HMAC-SHA256 over iterations iterations.

Procedure: random-bytes OPT: length

Return a bytevector of length cryptographically strong random bytes.

1.3.3 Variables

Variable: default-argon2id-iterations
3
Variable: default-argon2id-kdf
((kdf . argon2id) (memory-kib . 65536) (iterations . 3) (parallelism . 1))
Variable: default-argon2id-memory-kib
65536
Variable: default-argon2id-parallelism
1
Variable: default-kdf
pbkdf2
Variable: gcm-nonce-length
12
Variable: gcm-salt-length
16

1.4 (bewaking password)

1.4.1 Overview

1.4.2 Procedures

Procedure: generate-strong-password KEY: #:length #:include-symbols

Generate a random password designed to be strong.

One character from each included class is guaranteed, the remainder is drawn from the full pool, and the result is shuffled so no positional bias remains.

#:key length: total password length (default 24). Must be at least as large as the number of included character classes. #:key include-symbols: when #t (default) symbols are part of the pool. #:returns: a freshly generated password string.

#:example (generate-strong-password) ; 24 chars, mixed classes (generate-strong-password #:length 32) (generate-strong-password #:length 16 #:include-symbols #f)

Procedure: hash-password KEY: #:password #:memory-kib #:iterations #:parallelism

Hash password with Argon2id and return a PHC string such as $argon2id$v=19$m=65536,t=3,p=1$...$....

A fresh 16-byte salt is drawn from the CSPRNG for every call, so hashing the same password twice gives two different strings; the parameters are recorded in the string, so ‘verify-password‘ needs no configuration to check it later.

#:key memory-kib: Argon2id memory cost in kibibytes (default 65536). #:key iterations: Argon2id passes (default 3). #:key parallelism: Argon2id lanes (default 1).

#:example (hash-password #:password "correct horse battery staple")

Procedure: password-character-classes password

Return the list of character classes present in password.

The returned symbols are drawn from: lowercase, uppercase, digit and symbol. Anything that is not a letter, digit or whitespace is treated as a symbol, so punctuation, math symbols and other printable non-alphanumeric characters are covered.

#:example (password-character-classes "Abc123!") ; => (lowercase uppercase digit symbol)

The password is walked once, accumulating the four flags; the previous version scanned the whole password once per class, which made this the most expensive part of ‘password-strength‘ for long passphrases.

Procedure: password-entropy KEY: #:password

Return the raw estimated entropy of password in bits.

The estimate is length * log2(pool-size), where the pool size is the sum of the sizes of every character class present in the password. This is a simple model of guessing difficulty, not a guarantee of strength; use ‘password-strength‘ for a penalty-adjusted score.

#:example (password-entropy #:password "Tr0ub4dor&3") ; => a number of bits

Procedure: password-hash? value

Return #t when value is a well-formed Argon2id PHC hash string, as produced by ‘hash-password‘.

Procedure: password-strength KEY: #:password

Measure the strength of password and return an association list describing the result.

The estimate starts from ‘password-entropy‘, then applies penalties for common passwords, short lengths, repeated characters and sequential runs. A common password always scores 0.

The returned alist contains: - score: integer 0 (very weak) to 4 (very strong) - label: human-readable label for the score - entropy: penalty-adjusted entropy estimate, in bits - raw-entropy: unpenalized entropy estimate, in bits - length: length of the password - classes: character classes detected (list of symbols) - feedback: list of suggestions to improve the password

#:example (password-strength #:password "correct horse battery staple")

Procedure: password-strength-label score

Return a human-readable label for a numeric strength score between 0 and 4.

Procedure: strong-password? KEY: #:password #:min-score

Return #t when password scores at least min-score (default 3, "strong") according to ‘password-strength‘, otherwise #f.

#:example (strong-password? #:password "Tr0ub4dor&3") ; => #t or #f (strong-password? #:password "123456" #:min-score 4) ; => #f

Procedure: verify-password KEY: #:password #:hash #:max-memory-kib #:max-iterations

Return #t when password is the one hash was made from, and #f otherwise — including when hash is not a hash this library wrote.

The recorded cost is refused, not obeyed, when it is beyond max-memory-kib or max-iterations: a hash normally arrives from storage or from a client, and a 4 GiB memory cost would be a denial of service rather than a credential. The comparison itself is constant-time.

#:example (verify-password #:password attempt #:hash stored-hash)