- Store and check a password with bcrypt
- Verify a webhook HMAC signature
- Generate a password and measure its strength
- Signed licence key checked offline
- Field-level encryption of an IBAN with key escrow
- Audit of Unix file permissions
- Subnet of a CIDR block and firewall check
- Collision risk of random identifiers
- Detect credential stuffing on the login page
- Tamper-evident audit log with a hash chain
- Encrypt a sensitive field with AES-256-GCM and check the signature of a webhook
- Add a second factor to a login: secret, enrolment QR code, code check
- Check a source address against an allow list of networks
- Sign a PDF and check it: not modified is not the same as trusted
- Check that a webhook really comes from Stripe
- Accept only the tokens of your identity provider
- Store a password with Argon2id and sign a licence with Ed25519
- Check a certificate against its root and prepare its renewal
- Issue API keys and store passwords without keeping any secret in clear
- Decide what to do with a received invoice mail: SPF, DKIM and DMARC
- Remove the bank details and an address from a PDF invoice before it is shared
- Slow down password guessing on a login API with a limit per address and per account
Store and check a password with bcrypt
At sign-up a password is hashed with bcrypt (cost 10); at login it is verified. The script shows the salted hash, reads its cost factor, verifies a right and a wrong password, and contrasts it with an unsalted SHA-256.
#1. Hash the password at sign-up, cost 10; -> "[hash]" (string bcrypt_hash "Tr0ub4dor&3" 10); #2. Login attempts: right and wrong password; -> "[ok]" (string bcrypt_verify "Tr0ub4dor&3" [hash]); -> "[ko]" (string bcrypt_verify "tr0ub4dor&3" [hash]); #3. Never store a fast hash: compare with SHA-256; concat "{\"bcrypt\": \"" [hash] "\", \"length\": " (string length [hash]) ", \"cost\": " (string regexp_extract [hash] "^\$2a\$([0-9]+)\$" 1) ", \"login_ok\": " [ok] ", \"login_wrong_case\": " [ko] ", \"sha256_unsalted\": \"" (string sha_256 "Tr0ub4dor&3") "\"}";
{"bcrypt": "$2a$10$OY5CaYzycZ7wviYLHzU9R./TZq8zXEBGEiBcNDeWX46w6AqRKcx7y", "length": 60, "cost": 10, "login_ok": 1, "login_wrong_case": 0, "sha256_unsalted": "48486e1514e842346ff405b1e45f44059ae82619f2306f99d0940dcb386e91f7"}- The hash changes at every run because of the random salt: that is expected
- Raise the cost to 12 when the server gets faster, and rehash at the next login
Verify a webhook HMAC signature
A payment provider posts a webhook with a header 'sha256=...' computed as HMAC SHA-256 of 'timestamp.body' with a shared secret. The script recomputes the signature, accepts the genuine body and rejects a body whose amount was changed.
#1. Webhook received: timestamp, raw body and signature header; -> "[ts]" "1793520000"; -> "[body]" "{\"event\":\"payment.succeeded\",\"id\":\"evt_1042\",\"amount\":4990}"; -> "[header]" "sha256=4ca5bb3ebb5a24e5a70d949ca924b5348d600112726a3921bb1e3203e5aed2c6"; -> "[secret]" "whsec_9f8e7d6c"; #2. Expected signature of the genuine and of a tampered body; -> "[sig]" (concat "sha256=" (string hmac_sha256 (concat [ts] "." [body]) [secret])); -> "[bad]" (concat "sha256=" (string hmac_sha256 (concat [ts] "." (string replace [body] "4990" "1")) [secret])); #3. Accept or reject, and fingerprint the payload for the audit log; concat "{\"genuine_valid\": " (string equals_ignore_case [header] [sig]) ", \"tampered_valid\": " (string equals_ignore_case [header] [bad]) ", \"body_sha256\": \"" (string sha_256 [body]) "\"}";
{"genuine_valid": 1, "tampered_valid": 0, "body_sha256": "6c92459694aba28f0c8862409d884c47b3f24a6be75d17acaf18dd39e1e74582"}- Reject old replays: compare the timestamp with
date current_msand a 5-minute tolerance - Sign your own outgoing webhooks with the same
string hmac_sha256call
Generate a password and measure its strength
A service account needs a random password. The script generates 16 characters, counts the character classes it contains (lower, upper, digit, symbol) and computes its entropy in bits, compared with an 8-letter lowercase password.
#1. Generate a 16-character password; -> "[pwd]" (string generate_random_str 16); #2. Character classes present; -> "[cls]" (+ (string regexp [pwd] ".*[a-z].*") (string regexp [pwd] ".*[A-Z].*") (string regexp [pwd] ".*[0-9].*") (string regexp [pwd] ".*[^A-Za-z0-9].*")); #3. Entropy of a random string over an alphabet of 62; -> "[bits]" (math round (math calc "16*log(62)/log(2)") 1); concat "{\"password\": \"" [pwd] "\", \"classes\": " [cls] ", \"entropy_bits\": " [bits] ", \"weak_example_bits\": " (math round (math calc "8*log(26)/log(2)") 1) "}";
{"password": "mU35Yx8ftlXiEpeR", "classes": 3, "entropy_bits": 95.3, "weak_example_bits": 37.6}- The generated password changes at every run
- Reject passwords close to a known leaked one with
string levenshtein_distance
Signed licence key checked offline
A software vendor issues licence keys. The licence JSON is signed with the private key of the vendor; the installed product, which only knows the public key, verifies the key offline. A key edited by the customer (25 seats changed to 250) is rejected.
#1. The vendor key pair, the private key stays on the licence server; json load "rx_kp" (string encode_sign_generate_keypair "2048"); #2. Licence of a customer, signed with the private key; -> "[lic]" (concat "{\"customer\": \"ACME Reunion\", \"plan\": \"enterprise\", \"seats\": 25, \"expires\": \"" (date add "2026-11-01" "YEAR" 1) "\"}"); -> "[sig]" (string encode_sign [lic] (json select "rx_kp" "/privateKey")); -> "[key]" (concat (string encode_b64 [lic]) "." [sig]); #3. The installed product only knows the public key and its fingerprint; -> "[pub]" (json select "rx_kp" "/publicKey"); -> "[fp]" (string left (string sha_512 [pub]) 16); -> "[pinned]" [fp]; -> "[body]" (string decode_b64 (atom get [key] 1 ".")); -> "[ok]" (string decode_sign_verify [body] (atom get [key] 2 ".") [pub]); #4. A customer edits the seats to 250 and keeps the signature; -> "[forged]" (string replace [body] "\"seats\": 25" "\"seats\": 250"); -> "[ko]" (string decode_sign_verify [forged] (atom get [key] 2 ".") [pub]); json load "rx_lic" [body]; -> "[out]" (concat "{\"genuine\": " [ok] ", \"forged\": " [ko] ", \"expires\": \"" (json select "rx_lic" "/expires") "\", \"still_valid\": " (date is_after (json select "rx_lic" "/expires") "2026-11-01") ", \"pubkey_pinned\": " (equal [fp] [pinned]) ", \"licence_key_parts\": " (+ (string count [key] ".") 1) "}"); json unload "rx_kp"; json unload "rx_lic"; [out]
{"genuine": 1, "forged": 0, "expires": "2027-11-01", "still_valid": 1, "pubkey_pinned": 1, "licence_key_parts": 2}- Never ship the private key: the product embeds only the public key and its
string sha_512fingerprint - Add the machine id to the signed JSON to bind the licence to one server
Field-level encryption of an IBAN with key escrow
The payroll table must not store IBANs in clear. The IBAN is encrypted with a random master password (PBE), the master password is escrowed with the RSA key pair of the security officer, and a recovery decrypts both. Screens get a masked IBAN, searches use a hash.
#1. Field-level encryption of an employee IBAN before it goes into the payroll table; -> "[iban]" "FR7630006000011234567890189"; -> "[master]" (string generate_random_str 24); -> "[cipher]" (string encode_pbe [iban] [master]); #2. The master password is escrowed: encrypted with the RSA key pair of the security officer; json load "rx_rsa" (string encode_rsa_generate_keypair "2048"); -> "[escrow]" (string encode_rsa [master] (json select "rx_rsa" "/publicKey") (json select "rx_rsa" "/privateKey")); #3. Recovery: the officer decrypts the master password, then the IBAN; -> "[master2]" (string decode_rsa [escrow] (json select "rx_rsa" "/privateKey")); -> "[iban2]" (string decode_pbe [cipher] [master2]); #4. What the table and the screens can show; json load "rx_c" [cipher]; -> "[out]" (concat "{\"stored_fields\": " (string regexp_replace (json fields "rx_c" "/") "\s" "") ", \"plain_in_cipher\": " (string contains [cipher] "FR76") ", \"escrow_recovered\": " (equal [master2] [master]) ", \"iban_recovered\": " (equal [iban2] [iban]) ", \"iban_ok\": " (type is_iban [iban2]) ", \"masked\": \"" (string left [iban2] 4) (string repeat "*" 19) (string right [iban2] 4) "\", \"lookup_hash\": \"" (string left (string sha_256 [iban]) 12) "\"}"); json unload "rx_rsa"; json unload "rx_c"; [out]
{"stored_fields": ["encrypted","params"], "plain_in_cipher": 0, "escrow_recovered": 1, "iban_recovered": 1, "iban_ok": 1, "masked": "FR76*******************0189", "lookup_hash": "2847f6106ab6"}- Keep the master password in a private parameter, never in the script
- A plain SHA-256 of an IBAN can be brute-forced: prefer
string hmac_sha256with a secret for the lookup column
Audit of Unix file permissions
The hardening script of a web server reads the octal modes of sensitive files. The script converts each mode to an integer, tests the world-writable, setuid and world-readable bits with AND, proposes the fixed mode with AND NOT umask 022 and prints it back in octal.
#1. Modes in octal read by the audit script on a web server, the default umask is 022; json load "rx_fs" "{\"/var/www/app/config.php\": \"0666\", \"/var/www/app/index.php\": \"0644\", \"/usr/local/bin/backup\": \"4755\", \"/var/www/uploads\": \"0777\", \"/etc/app/secret.key\": \"0640\"}"; -> "[umask]" 18; -> "[out]" (concat "new file mode 666 AND NOT 022 = " (string int_to_oct (math bit_and 438 (math bit_xor 511 [umask]))) "; "); json parse_obj "rx_fs" "/" "[path]" "[oct]" { #2. Octal string to integer, digit by digit; -> "[m]" 0; for (-> "[i]" 0) (< [i] 4) (++ "[i]") {-> "[m]" (+ (* [m] 8) (string mid [oct] [i] (+ [i] 1)));}; #3. Bits 2 = world writable, 2048 = setuid, 4 = world readable; -> "[f]" ""; if (> (math bit_and [m] 2) 0) {-> "[f]" (concat [f] " WORLD-WRITABLE");}; if (> (math bit_and [m] 2048) 0) {-> "[f]" (concat [f] " SETUID");}; if (and (string contains [path] "secret") (> (math bit_and [m] 4) 0)) {-> "[f]" (concat [f] " SECRET-READABLE");}; #4. Fix proposal: remove the write bit of group and others with AND NOT 022; if (not (equal [f] "")) {-> "[out]" (concat [out] [path] " " [oct] [f] " -> chmod " (string int_to_oct (math bit_and [m] (math bit_xor 4095 [umask]))) "; ");}; }; json unload "rx_fs"; [out]
new file mode 666 AND NOT 022 = 644; /var/www/uploads 0777 WORLD-WRITABLE -> chmod 755; /var/www/app/config.php 0666 WORLD-WRITABLE -> chmod 644; /usr/local/bin/backup 4755 SETUID -> chmod 4755;
- Setuid binaries must be listed and justified: a setuid script is a classic privilege escalation
- Run it on the output of
find / -perm -o+wcollected by the system team
Subnet of a CIDR block and firewall check
A firewall rule allows the admin network given as 10.20.37.14/21. The script converts the address to an exact 32-bit integer, computes the mask, the network and broadcast addresses with AND, OR and XOR, prints the network in dotted notation, the mask in hex, the usable hosts, and checks the source addresses of the last connections.
#1. Firewall rule: allow the admin network of 10.20.37.14/21, then check the source addresses of the last connections; -> "[cidr]" "10.20.37.14/21"; -> "[ip]" (atom get [cidr] 1 "/"); -> "[pfx]" (atom get [cidr] 2 "/"); #2. Exact 32-bit integers with bigdec: a.b.c.d = a.2^24 + b.2^16 + c.2^8 + d; -> "[n]" (bd+ (bd+ (bd* (atom get [ip] 1 ".") 16777216) (bd* (atom get [ip] 2 ".") 65536)) (bd+ (bd* (atom get [ip] 3 ".") 256) (atom get [ip] 4 "."))); #3. Mask = 2^32 - 2^ 32 - prefix, network = ip AND mask, broadcast = network OR the inverted mask; -> "[mask]" (bd- 4294967296 (bigdec pow 2 (- 32 [pfx]) 20)); -> "[net]" (math bit_and [n] [mask]); -> "[bc]" (math bit_or [net] (math bit_xor [mask] 4294967295)); #4. Network in dotted notation, then test of each source address; -> "[d]" ""; for (-> "[k]" 3) (>= [k] 0) (-- "[k]") {-> "[d]" (concat [d] (math bit_and (bigdec round (bigdec div [net] (bigdec pow 256 [k] 20) 30) 0 DOWN) 255) (if (> [k] 0) {".";} {"";}));}; json load "rx_src" "[\"10.20.39.200\", \"10.20.40.1\", \"10.20.32.7\", \"192.168.1.20\"]"; -> "[chk]" ""; json parse_array "rx_src" "/" "[s]" { -> "[x]" (bd+ (bd+ (bd* (atom get [s] 1 ".") 16777216) (bd* (atom get [s] 2 ".") 65536)) (bd+ (bd* (atom get [s] 3 ".") 256) (atom get [s] 4 "."))); -> "[chk]" (concat [chk] [s] (if (== (math bit_and [x] [mask]) [net]) {" allow";} {" deny";}) ", "); }; json unload "rx_src"; concat "network " [d] "/" [pfx] ", mask hex " (string int_to_hex [mask]) ", usable hosts " (- (- [bc] [net]) 1) " | " [chk]
network 10.20.32.0/21, mask hex fffff800, usable hosts 2046 | 10.20.39.200 allow, 10.20.40.1 deny, 10.20.32.7 allow, 192.168.1.20 deny,
- The /21 given with a host address (37.14) is normalised to its network 10.20.32.0
- Check the address format first with
type is_ipv4
Collision risk of random identifiers
Before choosing the format of random identifiers, the architect computes the birthday bound: the probability of at least one collision after one million ids, and the number of ids that gives a 1 pct risk, for 7-character base62 short links, 64-bit ids and 128-bit tokens. expm1 and log1p keep the digits of tiny probabilities.
#1. How many identifiers can be issued before a collision becomes likely: short links of 7 base62 chars, 64-bit ids, 128-bit tokens; json load "rx_sp" "{\"short link 62^7\": 3.52161103e12, \"64-bit id\": 1.8446744073709552e19, \"128-bit token\": 3.402823669209385e38}"; -> "[issued]" 1000000; -> "[out]" ""; json parse_obj "rx_sp" "/" "[name]" "[N]" { #2. Birthday bound p = 1 - e^ -n.n-1 / 2N, computed as - expm1 so that tiny values keep their digits; -> "[p]" (* -1 (math expm1 (/ (* -1 (* [issued] (- [issued] 1))) (* 2 [N])))); #3. Number of ids for a 1 pct collision risk: n = sqrt of 2N ln of 1 / 1 - 0.01; -> "[n1]" (math sqrt (* (* 2 [N]) (* -1 (math log1p -0.01)))); -> "[out]" (concat [out] [name] ": P collision after 1M ids " [p] ", 1 pct risk after " (math round [n1] 0) " ids; "); }; json unload "rx_sp"; [out]
64-bit id: P collision after 1M ids 2.7105026839742053E-8, 1 pct risk after 6.08926881E8 ids; short link 62^7: P collision after 1M ids 0.13236167817948616, 1 pct risk after 266058 ids; 128-bit token: P collision after 1M ids 1.4693664691599209E-27, 1 pct risk after 2.615321040553087E18 ids;
- 7 base62 chars collide with 13 pct probability after 1M links: check the database or use more characters
- With 1 - exp(...) in plain doubles the 128-bit result would be 0, expm1 gives 1.47E-27
Detect credential stuffing on the login page
The SOC monitors the failed logins per minute. The baseline of the month is 4 per minute with a standard deviation of 1.5. The script runs a z-test on the last 12 minutes, counts the minutes above 3 sigma, finds the start of the attack and raises an alert.
#1. Failed logins per minute on the portal over the last 12 minutes, the baseline of the month is 4 per minute, sd 1.5; -> "[fails]" "[5, 3, 6, 4, 9, 14, 17, 15, 19, 16, 18, 21]"; -> "[mu]" 4; -> "[sigma]" 1.5; #2. z-test of the window against the baseline; json load "rx_z" (stat ztest [fails] [mu] [sigma]); #3. Minutes above 3 sigma, the first one is the start of the attack; json load "rx_f" [fails]; -> "[hot]" 0; -> "[start]" -1; for (-> "[i]" 0) (< [i] (json count "rx_f" "/")) (++ "[i]") { if (> (/ (- (json select "rx_f" (concat "/[" [i] "]")) [mu]) [sigma]) 3) {-> "[hot]" (+ [hot] 1); if (== [start] -1) {-> "[start]" [i];};}; }; -> "[out]" (concat "mean " (math round (stat mean [fails]) 2) " per min, z " (math round (json select "rx_z" "/z") 2) ", p " (if (< (json select "rx_z" "/p_value") 0.000001) {"< 1e-6";} {json select "rx_z" "/p_value";}) ", minutes over 3 sigma " [hot] ", attack from minute " (+ [start] 1) " of 12" " | " (if (< (json select "rx_z" "/p_value") 0.001) {"ALERT: credential stuffing, enable the CAPTCHA and rate limit by IP";} {"normal";})); json unload "rx_z"; json unload "rx_f"; [out]
mean 12.25 per min, z 19.05, p < 1e-6, minutes over 3 sigma 8, attack from minute 5 of 12 | ALERT: credential stuffing, enable the CAPTCHA and rate limit by IP
- Run it every minute with a job and write the alert with
log write - Group the failures by source IP and by user: stuffing means many users from few IPs
Tamper-evident audit log with a hash chain
Each line of an audit log is chained to the previous one: hash = SHA-256(previous hash + line). An intruder rewrites a line afterwards; the verification recomputes the chain from the genesis value and stops at the first broken link, even though the edited line looks plausible.
#1. Audit log where each line stores the SHA-256 of the previous hash + its own text, the chain starts from a genesis value; json load "rx_log" "[\"2026-10-31 08:02 login admin ok\", \"2026-10-31 08:05 role change user42 to auditor\", \"2026-10-31 08:09 export payroll.csv\", \"2026-10-31 08:15 logout admin\"]"; -> "[h]" (string sha_256 "genesis"); json load "rx_h" "[]"; json parse_array "rx_log" "/" "[l]" {-> "[h]" (string sha_256 (concat [h] [l])); json iarray "rx_h" "/" [h] STR;}; #2. An intruder edits line 2 afterwards to hide the role change; json uarray "rx_log" "/" 1 "2026-10-31 08:05 password reset user42" STR; #3. Verification recomputes the chain and stops at the first broken link; -> "[h]" (string sha_256 "genesis"); -> "[bad]" 0; for (-> "[i]" 0) (< [i] (json count "rx_log" "/")) (++ "[i]") { -> "[h]" (string sha_256 (concat [h] (json select "rx_log" (concat "/[" [i] "]")))); if (and (== [bad] 0) (not (equal [h] (json select "rx_h" (concat "/[" [i] "]"))))) {-> "[bad]" (+ [i] 1);}; }; -> "[out]" (concat "anchor " (string left (json select "rx_h" "/[3]") 16) "... | first broken line " [bad] ": " (json select "rx_log" (concat "/[" (- [bad] 1) "]"))); json unload "rx_log"; json unload "rx_h"; [out]
anchor c4de521b2ac6a524... | first broken line 2: 2026-10-31 08:05 password reset user42
- Publish the last hash (the anchor) every day outside the server: an attacker cannot rebuild the whole chain unseen
- Sign the anchor with
string encode_signto prove who closed the day
Encrypt a sensitive field with AES-256-GCM and check the signature of a webhook
An IBAN must be stored encrypted in the database (AES-256-GCM: confidential and tamper-proof), with a key kept outside the scripts. A payment provider calls a webhook with an HMAC-SHA256 signature of the body: it is checked in constant time before trusting the message. A random token (base64url) identifies the request.
#In production the key comes from a protected file or a vault; -> "[key]" (string generate_key_aes); -> "[stored]" (string encrypt_aes "FR7630006000011234567890189" [key] "{\"aad\": \"customer:C001\"}"); -> "[iban]" (string decrypt_aes [stored] [key] "{\"aad\": \"customer:C001\"}"); try {-> "[moved]" (string decrypt_aes [stored] [key] "{\"aad\": \"customer:C002\"}");} {-> "[moved]" "refused";} "[e]"; #The webhook: body and signature sent by the provider; -> "[body]" "{\"event\": \"payment.succeeded\", \"amount\": 4990}"; -> "[sig]" (string hmac "sha256" [body] "whsec_test_secret"); -> "[res]" (concat "stored: " (string left [stored] 3) "... (" (string length [stored]) " chars), read back " [iban] ", copied to another customer: " [moved] " | webhook valid " (string hmac_verify "sha256" [body] "whsec_test_secret" [sig]) ", forged " (string hmac_verify "sha256" (concat [body] " ") "whsec_test_secret" [sig]) " | token of " (string length (string random_bytes 24 "base64url")) " chars"); [res]
stored: v1:... (79 chars), read back FR7630006000011234567890189, copied to another customer: refused | webhook valid 1, forged 0 | token of 32 chars
- The associated data (aad) ties the ciphertext to its customer: a value copied to another row cannot be decrypted.
- Each encryption uses a new random nonce: encrypting twice the same IBAN gives two different values.
Add a second factor to a login: secret, enrolment QR code, code check
TOTP is what authenticator apps use (Google Authenticator, Aegis, FreeOTP). The server keeps a secret per user; the code changes every 30 seconds. The time is fixed here so that the result does not change; in production it is omitted.
if (equal (file exist "tmp/rec_totp") "0") {file mkdir "tmp/rec_totp";}; -> "[secret]" "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; -> "[uri]" (totp uri [secret] "jean@acme.re" "ACME"); qr create [uri] "tmp/rec_totp/enrol.png"; json load "rec_r" (qr read "tmp/rec_totp/enrol.png"); -> "[scan_ok]" (equal (json select "rec_r" "/text") [uri]); json unload "rec_r"; -> "[code]" (totp code [secret] "{\"time\": 1793520000}"); -> "[ok]" (totp verify [secret] [code] "{\"time\": 1793520030}"); -> "[late]" (totp verify [secret] [code] "{\"time\": 1793520600}"); file delete "tmp/rec_totp"; -> "[res]" (concat "the app reads the link: " [scan_ok] " | code " [code] " | next period (window 1): " [ok] " | ten minutes later: " [late]); [res]
the app reads the link: 1 | code 201716 | next period (window 1): 1 | ten minutes later: 0
- totp secret generates the secret; store it encrypted, for example with string encrypt_aes.
- Refuse the same code twice on your side: a valid code stays valid during its window.
Check a source address against an allow list of networks
A filter on addresses must work on numbers, not on text: 192.168.1.100 begins like 192.168.1.1. The functions read IPv4 and IPv6 without any DNS request.
json load "rec_net" (ip cidr "10.20.0.0/22"); -> "[hosts]" (concat (json select "rec_net" "/first") " to " (json select "rec_net" "/last")); json unload "rec_net"; json load "rec_i" (ip info "192.168.1.100"); -> "[private]" (json select "rec_i" "/private"); json unload "rec_i"; -> "[res]" (concat "network " [hosts] " | 10.20.3.7 allowed: " (ip in_cidr "10.20.3.7" "10.20.0.0/22") " | 10.20.4.1 allowed: " (ip in_cidr "10.20.4.1" "10.20.0.0/22") " | IPv6 allowed: " (ip in_cidr "2001:db8::5" "2001:db8::/32") " | private: " [private]); [res]
network 10.20.0.1 to 10.20.3.254 | 10.20.3.7 allowed: 1 | 10.20.4.1 allowed: 0 | IPv6 allowed: 1 | private: true
- tls certificate and tcp check complete a supervision: days before expiry and open ports.
Sign a PDF and check it: not modified is not the same as trusted
A signature protects the bytes that it covers, but anybody can sign with a certificate of their own. So valid is true only when the document is not modified and the signer is in your trust store. Without a trust store, as here with a self-signed test certificate, the status is intact_untrusted; for real use, take a certificate from a certification authority and give its chain as the trust_store parameter.
if (equal (file exist "tmp/rec_sign") "0") {file mkdir "tmp/rec_sign";}; secret set "rec_sign_key" "test-only-password"; sign create_test_keystore "tmp/rec_sign/test.p12" "{\"password\": \"rec_sign_key\", \"subject\": \"CN=Test Signer,O=Demo\", \"days\": 30, \"overwrite\": true}"; pdf create "rec_s"; pdf page add "rec_s" "A4" "portrait"; pdf text add "rec_s" 1 40 40 "Invoice F2026-0042, total 1250.00 EUR" "font=HELVETICA_BOLD;size=14"; pdf save "rec_s" "tmp/rec_sign/in.pdf"; pdf close "rec_s"; pdf sign "tmp/rec_sign/in.pdf" "tmp/rec_sign/signed.pdf" "tmp/rec_sign/test.p12" "{\"password\": \"rec_sign_key\", \"reason\": \"Approval\"}"; json load "rec_v" (pdf verify_signatures "tmp/rec_sign/signed.pdf"); -> "[status]" (json select "rec_v" "/status"); -> "[intact]" (json select "rec_v" "/integrity_ok"); -> "[valid]" (json select "rec_v" "/valid"); json unload "rec_v"; file delete "tmp/rec_sign"; -> "[res]" (concat "status: " [status] " | not modified: " [intact] " | valid: " [valid]); [res]
status: intact_untrusted | not modified: true | valid: false
- This is an advanced electronic signature. A qualified eIDAS signature needs a qualified certificate and device from a provider.
- xml sign and xml verify_signature do the same for XML, with the XAdES option.
Check that a webhook really comes from Stripe
A webhook address is public: anybody can send it a fake payment confirmation. The signature proves who sent the request, and the signed timestamp stops somebody from sending again a request captured earlier. Here the three cases are shown: the true one, a modified body, and a replay one hour later. The signing is done locally, with a test secret, to play the role of the sender.
-> "[secret]" "whsec_test_only"; -> "[body]" "{\"id\": \"evt_1\", \"type\": \"invoice.paid\"}"; -> "[header]" (webhook sign "stripe" [body] [secret] "{\"timestamp\": 1800000000}"); json load "rec_a" (webhook verify "stripe" [body] [header] [secret] "{\"now\": 1800000010}"); -> "[good]" (json select "rec_a" "/valid"); json unload "rec_a"; json load "rec_b" (webhook verify "stripe" (concat [body] " ") [header] [secret] "{\"now\": 1800000010}"); -> "[changed]" (json select "rec_b" "/error"); json unload "rec_b"; json load "rec_c" (webhook verify "stripe" [body] [header] [secret] "{\"now\": 1800003600}"); -> "[replay]" (json select "rec_c" "/error"); json unload "rec_c"; -> "[res]" (concat "true request: " [good] " | modified: " [changed] " | one hour later: " [replay]); [res]
true request: true | modified: the signature does not match | one hour later: the timestamp is outside the tolerance of 300 s
- GitHub and Slack work the same way, and generic covers the other senders (Shopify: encoding base64). GitHub signs no timestamp: replay_protected is false in its result.
- Give the raw body as received: a body that was parsed and written again no longer has the same bytes.
Accept only the tokens of your identity provider
Behind an identity provider (Keycloak, Auth0, Entra ID...), an API receives signed tokens and checks them with the public keys that the provider publishes. In production the second argument is the https address of the JWKS, and the keys are cached. Here the JWKS is given as JSON so that the recipe runs alone. The classic attack, a token that says alg none, is refused like an expired one.
-> "[jwks]" "{\"keys\": [{\"crv\": \"P-256\", \"kid\": \"k1\", \"kty\": \"EC\", \"x\": \"MZMSHEp2Ztg5uyopM0ORZBJPb6xWebleJoIxG2wyFq4\", \"y\": \"ZUifIROzhc3ghnsDY43gLBcbhMGxL3YFkSYYuqRWBOc\", \"use\": \"sig\", \"alg\": \"ES256\"}]}"; -> "[check]" "{\"issuer\": \"https://login.example.com\", \"audience\": \"api\", \"now\": 1800000000, \"leeway\": 0}"; json load "rec_a" (jwt verify_jwks "eyJhbGciOiJFUzI1NiIsImtpZCI6ImsxIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUuY29tIiwiYXVkIjoiYXBpIiwic3ViIjoidTQyIiwiZXhwIjo0MTAyNDQ0ODAwfQ.XMdQbsQ_0nOmHyJdYxXOhpljCjV5khicokIabeDaYBnc62bL5T2qTheO3wTBxCl2YCBMUXwAx-M6-LAIziWZZw" [jwks] [check]); -> "[user]" (json select "rec_a" "/claims/sub"); -> "[valid]" (json select "rec_a" "/valid"); json unload "rec_a"; json load "rec_b" (jwt verify_jwks "eyJhbGciOiJFUzI1NiIsImtpZCI6ImsxIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUuY29tIiwiYXVkIjoiYXBpIiwic3ViIjoidTQyIiwiZXhwIjoxNzAwMDAwMDAwfQ.XwuOLDgrvDBXGC5fRL7MeD70KlX5ynM8GdwsiZVlGJjbUp9Cy8biTSox-VdoaBXSTNsiRSsE-eBz_0jZw5JHtA" [jwks] [check]); -> "[late]" (json select "rec_b" "/error"); json unload "rec_b"; json load "rec_c" (jwt verify_jwks "eyJhbGciOiJub25lIiwia2lkIjoiazEifQ.eyJpc3MiOiAiaHR0cHM6Ly9sb2dpbi5leGFtcGxlLmNvbSIsICJhdWQiOiAiYXBpIiwgInN1YiI6ICJ1NDIiLCAiZXhwIjogNDEwMjQ0NDgwMH0." [jwks] [check]); -> "[none]" (json select "rec_c" "/error"); json unload "rec_c"; -> "[res]" (concat "valid: " [valid] " for user " [user] " | expired: " [late] " | forged: " [none]); [res]
valid: true for user u42 | expired: the token expired at 1700000000 (now 1800000000) | forged: the algorithm none is refused
- Always give issuer and audience: without them, a token made for another application of the same provider would pass.
- oauth discover gives the jwks_uri of a provider from its issuer address.
Store a password with Argon2id and sign a licence with Ed25519
Two common needs with modern algorithms. A password is stored only as an Argon2id text, which holds its salt and its costs. A licence is signed with a private key that stays at home, and any server with the public key can check it: a single changed character makes the signature fail.
-> "[hash]" (string argon2_hash "correct horse" "{\"memory_kib\": 8192, \"iterations\": 2, \"parallelism\": 1}"); -> "[right]" (string argon2_verify "correct horse" [hash]); -> "[wrong]" (string argon2_verify "battery staple" [hash]); json load "rec_k" (ed25519 generate_keys); -> "[private]" (json select "rec_k" "/private_key"); -> "[public]" (json select "rec_k" "/public_key"); json unload "rec_k"; -> "[licence]" "customer=ACME;until=2027-12-31"; -> "[signature]" (ed25519 sign [licence] [private]); -> "[good]" (ed25519 verify [licence] [signature] [public]); -> "[forged]" (ed25519 verify "customer=ACME;until=2099-12-31" [signature] [public]); -> "[res]" (concat "right password: " [right] " | wrong password: " [wrong] " | licence: " [good] " | changed licence: " [forged]); [res]
right password: 1 | wrong password: 0 | licence: 1 | changed licence: 0
- In real use take the default costs of string argon2_hash, which need 64 MiB for each check, and keep the private key out of the scripts.
Check a certificate against its root and prepare its renewal
Before a certificate expires, read its dates, check that it still goes up to the trusted root, and prepare a request for the authority. The dates are fixed here so that the result does not change: without now, the current date is used. Revocation is not checked: the result says so.
-> "[leaf]" "-----BEGIN CERTIFICATE-----\nMIIBVDCCAQagAwIBAgICEAEwBQYDK2VwMCMxDTALBgNVBAoMBERlbW8xEjAQBgNV\nBAMMCURlbW8gUm9vdDAeFw0yNjAxMDEwMDAwMDBaFw0yNzAxMDEwMDAwMDBaMCsx\nDTALBgNVBAoMBERlbW8xGjAYBgNVBAMMEXNob3AuZXhhbXBsZS50ZXN0MCowBQYD\nK2VwAyEARUNur3/L5N1StyJq7oJv1aiGXHmgWPj5vkXCPvbCQsGjVjBUMAkGA1Ud\nEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMBMCIGA1Ud\nEQQbMBmCEXNob3AuZXhhbXBsZS50ZXN0hwTAAAIKMAUGAytlcANBAA+zfyhzz8Y4\n88wQzYt4nsTTxnBw5njJWbpTNOFfJwuUk617BT9S5WkFq2mraS/ilXsBRJ41YbWK\na8U6ZtF53A0=\n-----END CERTIFICATE-----"; -> "[root]" "-----BEGIN CERTIFICATE-----\nMIIBSTCB/KADAgECAhRA4hi0kxsjg28Gzbw5He4AjblZqjAFBgMrZXAwIzENMAsG\nA1UECgwERGVtbzESMBAGA1UEAwwJRGVtbyBSb290MB4XDTI2MDEwMTAwMDAwMFoX\nDTM2MDEwMTAwMDAwMFowIzENMAsGA1UECgwERGVtbzESMBAGA1UEAwwJRGVtbyBS\nb290MCowBQYDK2VwAyEA41MG1NJzimK4o3X5q2njln1PLGGQVYxEDu0SWmwutRuj\nQjBAMB0GA1UdDgQWBBRIrb31QisSFpRapyEB28VPj64tGzAPBgNVHRMBAf8EBTAD\nAQH/MA4GA1UdDwEB/wQEAwICBDAFBgMrZXADQQCbXmKrbx9WK8AQ7rkhKckXQrkC\nBXiqG5NyLj7rynPGtAcSUxnTiEBMs20PYURAySIuSrxKbGt5mNCAtz/tMhoN\n-----END CERTIFICATE-----"; json load "rec_p" (cert parse [leaf] "{\"now\": \"2026-11-05T00:00:00Z\"}"); -> "[subject]" (json select "rec_p" "/certificates/[0]/subject"); -> "[days]" (json select "rec_p" "/certificates/[0]/days_left"); json unload "rec_p"; json load "rec_v" (cert chain_verify [leaf] [root] "{\"now\": \"2026-11-05T00:00:00Z\"}"); -> "[now_ok]" (json select "rec_v" "/valid"); json unload "rec_v"; json load "rec_l" (cert chain_verify [leaf] [root] "{\"now\": \"2028-01-01T00:00:00Z\"}"); -> "[later]" (json select "rec_l" "/reason"); json unload "rec_l"; json load "rec_c" (cert csr "{\"subject\": \"CN=shop.example.test,O=Demo\", \"san\": [\"shop.example.test\"], \"extended_key_usage\": [\"serverAuth\"]}"); -> "[csr]" (json select "rec_c" "/csr"); json unload "rec_c"; json load "rec_r" (cert csr_parse [csr]); -> "[signed]" (json select "rec_r" "/signature_valid"); json unload "rec_r"; -> "[res]" (concat [subject] " | days left: " [days] " | chain today: " [now_ok] " | in 2028: " [later] " | new request signed: " [signed]); [res]
CN=shop.example.test,O=Demo | days left: 57 | chain today: true | in 2028: expired | new request signed: true
- tls certificate reads the certificate of a running server. The private key that cert csr returns must be stored safely: the parameter private_key_file writes it in a file for its owner only.
Issue API keys and store passwords without keeping any secret in clear
A customer portal gives each partner an API key and each user a password. The key is shown once, then only a keyed BLAKE2b fingerprint is stored (the server secret comes from the configuration, not from the database), with a short public reference in Base58 for the support. The password is stored as an scrypt text, which holds its own salt and costs.
-> "[server_secret]" "change-me-in-the-configuration"; -> "[api_key]" (concat "pk_" (string nanoid "{\"size\": 32}")); -> "[params]" (concat "{\"key\": \"" [server_secret] "\", \"size\": 32}"); -> "[stored]" (string blake2b [api_key] [params]); -> "[again]" (string blake2b [api_key] [params]); -> "[reference]" (string encode_b58 (string substr [stored] 0 16) "{\"input_encoding\": \"hex\"}"); -> "[hash]" (string scrypt_hash "correct horse battery" "{\"ln\": 14}"); -> "[right]" (string scrypt_verify "correct horse battery" [hash]); -> "[wrong]" (string scrypt_verify "correct horse" [hash]); -> "[res]" (concat "key length " (string length [api_key]) " | same fingerprint at each call: " (equal [stored] [again]) " | reference decodes back: " (equal (string decode_b58 [reference] "{\"output_encoding\": \"hex\"}") (string substr [stored] 0 16)) " | right password: " [right] " | wrong password: " [wrong]); [res]
key length 35 | same fingerprint at each call: 1 | reference decodes back: 1 | right password: 1 | wrong password: 0
- ln 14 keeps this example fast; for real passwords keep the default ln 16 (64 MiB) or more, as far as the server memory allows.
- string blake3 with derive_key_context derives one key per use from a master secret. xxHash is not a security hash: use it only to partition or to detect accidental changes.
Decide what to do with a received invoice mail: SPF, DKIM and DMARC
A fake invoice that asks to pay to another bank account is a classic fraud. A receiving server checks three things: SPF (is the sending server allowed by the domain of the envelope?), DKIM (is the message signed by the domain, and unchanged?), and DMARC (does one of them pass for the domain shown in From, and what does the domain ask to do otherwise?). Here the sender signs with a test key, then the true message, a message whose body was changed, and a message sent from an unknown server are checked. The DNS answers are given in records, so that the recipe runs offline.
-> "[dns]" "{\"records\": {\"example.com\": {\"TXT\": [\"v=spf1 ip4:192.0.2.0/24 include:_spf.mailer.example.net -all\"]}, \"_spf.mailer.example.net\": {\"TXT\": [\"v=spf1 ip4:198.51.100.0/24 -all\"]}, \"_dmarc.example.com\": {\"TXT\": [\"v=DMARC1; p=reject; adkim=r; aspf=r; rua=mailto:dmarc@example.com\"]}, \"mail2026._domainkey.example.com\": {\"TXT\": [\"v=DKIM1; k=ed25519; p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=\"]}}}"; -> "[msg]" "From: Billing <billing@example.com>\nTo: client@example.net\nSubject: Invoice 2026-114\nDate: Tue, 10 Nov 2026 09:00:00 +0000\nMessage-ID: <inv-2026-114@example.com>\n\nYour invoice is attached.\n"; secret set "rec_dkim_key" "nWGxne/9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A="; -> "[signed]" (mail dkim_sign [msg] (concat "{\"domain\": \"example.com\", \"selector\": \"mail2026\", \"private_key\": \"rec_dkim_key\"}")); -> "[auth]" (concat "{\"spf\": " (mail spf_check "198.51.100.25" "bounce@example.com" [dns]) ", \"dkim\": " (mail dkim_verify [signed] [dns]) "}"); json load "rec_ok" (mail dmarc_evaluate "billing@example.com" [auth] [dns]); -> "[changed]" (string replace [signed] "Your invoice is attached." "New bank account: FR76 0000 0000 0000."); -> "[auth2]" (concat "{\"spf\": " (mail spf_check "203.0.113.66" "billing@example.com" [dns]) ", \"dkim\": " (mail dkim_verify [changed] [dns]) "}"); json load "rec_bad" (mail dmarc_evaluate "billing@example.com" [auth2] [dns]); -> "[res]" (concat "true mail: " (json select "rec_ok" "/dmarc") " (" (json select "rec_ok" "/reason") ") | changed and sent from elsewhere: " (json select "rec_bad" "/dmarc") ", " (json select "rec_bad" "/disposition")); json unload "rec_ok"; json unload "rec_bad"; [res]
true mail: pass (DKIM passes and is aligned (example.com)) | changed and sent from elsewhere: fail, reject
- The key used here is the public test key of RFC 8032: never use it. A real key is kept with secret set and named in private_key, or given by private_key_file, and the DNS record to publish comes from mail dkim_sign with output json.
- Without records, the functions ask the DNS of the server. A DNS that does not answer gives temperror: the usual decision is to try again later, not to reject.
Remove the bank details and an address from a PDF invoice before it is shared
An invoice must be sent to an auditor without the IBAN and without the address of the customer. Drawing a black box over them is not enough: the text stays in the file and any PDF reader can copy it. pdf redact removes the glyphs themselves from the page (the rest of the line keeps its place), blackens the images under the areas, then reads the new file again and refuses to write it if the text can still be found. pdf compare then lists the lines that changed between the original and the redacted copy.
if (equal (file exist "tmp/rec_ops_pdf") "1") {file delete "tmp/rec_ops_pdf";}; if (equal (file exist "tmp/rec_ops_pdf") "0") {file mkdir "tmp/rec_ops_pdf";}; invoice to_pdf "{\"number\": \"F2026-0207\", \"type_code\": \"380\", \"issue_date\": \"2026-11-10\", \"currency\": \"EUR\", \"seller\": {\"name\": \"Atelier Payet SARL\", \"siren\": \"732829320\", \"vat_id\": \"FR44732829320\", \"address\": {\"line1\": \"12 rue de Paris\", \"postcode\": \"97400\", \"city\": \"Saint-Denis\", \"country\": \"FR\"}}, \"buyer\": {\"name\": \"Client SAS\", \"address\": {\"line1\": \"8 avenue Foch\", \"postcode\": \"75008\", \"city\": \"Paris\", \"country\": \"FR\"}}, \"lines\": [{\"name\": \"Maintenance contract\", \"quantity\": 1, \"unit_price\": 480, \"vat_category\": \"S\", \"vat_rate\": 8.5}], \"payment\": {\"iban\": \"FR7630006000011234567890189\", \"terms\": \"30 days\"}}" "tmp/rec_ops_pdf/invoice.pdf"; json load "rp_red" (pdf redact "tmp/rec_ops_pdf/invoice.pdf" "tmp/rec_ops_pdf/invoice_redacted.pdf" "{\"patterns\": [\"FR76[0-9 ]+\", \"8 avenue Foch\"]}"); json load "rp_cmp" (pdf compare "tmp/rec_ops_pdf/invoice.pdf" "tmp/rec_ops_pdf/invoice_redacted.pdf"); -> "[res]" (concat "matches: " (json select "rp_red" "/matches") ", glyphs removed: " (json select "rp_red" "/glyphs_removed") ", verified: " (json select "rp_red" "/verified") " | changes: " (json select "rp_cmp" "/pages/[0]/changes")); json unload "rp_red"; json unload "rp_cmp"; if (equal (file exist "tmp/rec_ops_pdf") "1") {file delete "tmp/rec_ops_pdf";}; [res]
matches: 2, glyphs removed: 46, verified: true | changes: [
{
"line_a": 8,
"line_b": 8,
"lines_b": [],
"lines_a": [
"8 avenue Foch"
],
"type": "delete"
},
{
"line_a": 18,
"line_b": 17,
"lines_b": [
"IBAN:"
],
"lines_a": [
"IBAN: FR76 3000 6000 0112 3456 7890 189"
],
"type": "change"
}
]- Areas are given in points from the top left corner of the page: {"areas": [{"page": 1, "x": 40, "y": 700, "width": 200, "height": 40}]}.
- Text drawn as vector paths or inside a scanned image is not text: it cannot be found by a pattern. Check such files by eye.
Slow down password guessing on a login API with a limit per address and per account
A login API must not let a robot try thousands of passwords. Each attempt is counted twice: per client address (5 per minute) and per account (a token bucket of 3 attempts, refilled at 10 per hour), so that changing the address or the account alone does not help. Here seven attempts come from the same address on the same account: the first three pass, then the account is blocked, and the address is blocked after five. A refused request is not counted. After a successful login the counter of the account is reset. The answer to send is an HTTP 429 with Retry-After from retry_after_ms.
rate_limit reset "rec.login.ip:192.0.2.7"; rate_limit reset "rec.login.user:alice"; -> "[seen]" ""; for (-> "[i]" 1) (<= [i] 7) (++ "[i]") { json load "rx_ip" (rate_limit check "rec.login.ip:192.0.2.7" "5" "60"); json load "rx_u" (rate_limit check "rec.login.user:alice" "10" "3600" "{\"algorithm\": \"token_bucket\", \"burst\": 3}"); -> "[ok]" "pass"; if (equal (json select "rx_u" "/allowed") "false") {-> "[ok]" "429 account";}; if (equal (json select "rx_ip" "/allowed") "false") {-> "[ok]" "429 address";}; -> "[wait]" (> (json select "rx_ip" "/retry_after_ms") 0); -> "[seen]" (concat [seen] [i] ": " [ok] "; "); json unload "rx_ip"; json unload "rx_u"; }; json load "rx_s" (rate_limit status "rec.login.ip:192.0.2.7"); -> "[left]" (json select "rx_s" "/remaining"); json unload "rx_s"; -> "[reset]" (rate_limit reset "rec.login.user:alice"); json load "rx_s" (rate_limit status "rec.login.user:alice"); -> "[res]" (concat [seen] "| last attempt must wait: " [wait] " | attempts left for the address: " [left] " | account reset after a good password: " [reset] ", known now: " (json select "rx_s" "/found")); json unload "rx_s"; [res]
1: pass; 2: pass; 3: pass; 4: 429 account; 5: 429 account; 6: 429 address; 7: 429 address; | last attempt must wait: 1 | attempts left for the address: 0 | account reset after a good password: 1, known now: false
- Both checks are made at each attempt, so a refused address still costs a token of the account: an attacker who blocks an account blocks it for the real user too. Keep the account limit generous, and reset it after a successful login.
- The limiter keeps 100000 keys at most: a flood of new addresses makes the oldest ones forget their count. The limit per account protects against this case.
