crypto — hashes, signatures, base64
mzs
include cryptoINFO
Available in bot scripts, except crypto.random.
| Function | What it does |
|---|---|
crypto.sha256(s) | SHA-256, hex |
crypto.sha512(s), crypto.sha384(s) | SHA-512, SHA-384, hex |
crypto.sha1(s), crypto.md5(s) | SHA-1, MD5, hex — for old protocols |
crypto.hmac(key, msg) | HMAC-SHA256, hex |
crypto.hmac(key, msg, alg) | HMAC with "sha512", "sha384", "sha1", "md5" |
crypto.crc32(s) | CRC-32 checksum, int |
crypto.equal(a, b) | constant-time string comparison |
crypto.hex(s), crypto.unhex(s) | bytes → hex and back |
crypto.base64(s) | base64 |
crypto.base64(s, "url") | base64url without = (JWT, links) |
crypto.unbase64(s) | from base64 of either kind, with = or without |
crypto.random(n) | n cryptographically secure random bytes, hex; in the CLI, with the --rand flag |
Everything works on the string's bytes (UTF-8), not its characters.
Hashes
mzs
include crypto
crypto.sha256("hello") # → "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
crypto.md5("abc") # → "900150983cd24fb0d6963f7d28e17f72"
crypto.sha1("abc") # → "a9993e364706816aba3e25717850c26c9cd0d89d"
crypto.crc32("mzs") # → 2744266907HMAC signature
mzs
include crypto
crypto.hmac("s3cret", '{"id":7}') # → "c48dcba22b49a9371cdf607a41016238221e38c78d72e9eccb55c75bdc0f3ebc"
crypto.hmac("key", "msg", "sha1") # → "102900b72b7bf1031eec76b4804b66052376896b"Verifying a webhook
Compare signatures with crypto.equal, not ==: a plain comparison leaks through timing how many bytes matched.
mzs
include crypto
fn signed_ok(secret, body, signature) {
crypto.equal(crypto.hmac(secret, body), signature)
}
body = '{"order":42}'
sig = crypto.hmac("s3cret", body)
signed_ok("s3cret", body, sig) # → true
signed_ok("s3cret", body, "deadbeef") # → falseThe signature came in base64: turn yours into base64 and compare the strings:
mzs
include crypto
want = crypto.base64(crypto.unhex(crypto.hmac("k", "body")))
want # → "xtgR7zrrAkN81CPxq+EyCQQYZGML3E4sBN71x7ADGiM="base64 and hex
mzs
include crypto
crypto.base64("Привет") # → "0J/RgNC40LLQtdGC"
crypto.unbase64("0J/RgNC40LLQtdGC") # → "Привет"
crypto.base64("?~~~ ok") # → "P35+fiBvaw=="
crypto.base64("?~~~ ok", "url") # → "P35-fiBvaw"
crypto.unbase64("P35-fiBvaw") # → "?~~~ ok"
crypto.hex("é") # → "c3a9"
crypto.unhex("c3a9") # → "é"A JWT header:
mzs
include crypto
include json
json.parse(crypto.unbase64("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")) # → {"alg":"HS256","typ":"JWT"}Random token
mzs
include crypto
crypto.random(16).len # → 32Errors
mzs
include crypto
try crypto.unhex("abc") else (e) -> e["kind"] # → "argument"
try crypto.hmac("k", "m", "sha3") else (e) -> e["kind"] # → "argument"