Reference · Crypto

crypto.token

signature
crypto.token(int=) -> str

What it does

A random token from the operating system's random source, for session ids, API keys, reset links and secrets: that many random bytes (32 unless given, from 1 to 1,024) written in base64url, so it is safe in a URL, a cookie and a header without encoding. 32 bytes give 43 characters. It needs the random effect.

Examples

let t = crypto.token()print(len(t), re.test(t, "^[A-Za-z0-9_-]+$"))print(len(crypto.token(16)), len(crypto.token(64)))
output
43 true22 86

Edge cases

print(crypto.token() == crypto.token())print(len(crypto.token(1)), len(crypto.token(1024)))print(len(crypto.token(null)))print(crypto.token(9) | re.test("^[A-Za-z0-9_-]{12}$"))
output
false2 136643true

Errors

A size outside 1 to 1,024, or one that is not an int, is a runtime error, not an error value.

this one fails
print(crypto.token(0))
output
line 1: `crypto.token` takes a number of bytes from 1 to 1024, got 0
this one fails
print(crypto.token("32"))
output
line 1: `crypto.token` takes a number of bytes from 1 to 1024, got "32"

Chaining

The size is its only argument, so it is called plainly and its result piped on: into a slice for a shorter code, or stored beside its hash so the database never holds the secret itself.

let key = crypto.token()print(len(key), len(crypto.sha256(key)))print(crypto.token(6) | len)
output
43 648

See also

crypto.hash_password, crypto.sha256, crypto.equal, uuid, random

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

Thread 0 posts

On crypto.token(): 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