Reference · Crypto

crypto.equal

signature
crypto.equal(str, str) -> bool

What it does

Whether two strings are the same, taking the same time whether they differ in the first character or the last. == stops at the first difference, and the time it takes can tell an attacker how much of a guess was right; so a secret that came from outside (an API key, a webhook signature, a token in a link) is compared with this.

Examples

print(crypto.equal("abc", "abc"), crypto.equal("abc", "abd"))let tag = crypto.hmac("secret", "payload")print(crypto.equal(tag, crypto.hmac("secret", "payload")))
output
true falsetrue
in a program
route POST /hooks/pay {    let expected = crypto.hmac(env("HOOK_SECRET"), request.body)    if !crypto.equal(request.headers["x-signature"] ?? "", expected) { reply 401 "bad signature" }    ...}

Edge cases

print(crypto.equal("a", "ab"), crypto.equal("", ""))print(crypto.equal("ABC", "abc"))print(crypto.equal(null ?? "", "x"))
output
false truefalsefalse

Errors

An argument that is not a string, null included, is a runtime error, not an error value.

this one fails
print(crypto.equal("a", 1))
output
line 1: `crypto.equal` expects a str as argument 2, got int

Chaining

The first string pipes in; the result is a bool for if.

print("secret-key" | crypto.equal("secret-key"))print(["k1", "k2"] | filter((k) => crypto.equal(k, "k2")))
output
true["k2"]

See also

crypto.hmac, crypto.verify_password, crypto.token, crypto.sha256

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On crypto.equal(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo