Skip to content

Session tokens and signed values

For anything an attacker must not guess, use the secure random functions, never random.int, which is predictable.

  • random.token(n) gives n secure random bytes as URL-safe text. 16 bytes (22 characters) or more is a good session id.
  • hash.hmac_sha256(key, data) signs a value, so you can hand it out and later check that it came back unchanged.
  • hash.equal_secret(a, b) compares secrets in constant time, so the time a comparison takes does not reveal how many characters matched.
import hash
import random
let key = random.secure_bytes(32)
fn sign(key: &Str, value: &Str) -> Str {
return *value + "." + hash.hmac_sha256(key, value)
}
fn verify(key: &Str, signed: &Str) -> Option<Str> {
match signed.rsplit_once(".") {
Some((value, mac)) => {
if hash.equal_secret(&mac, &hash.hmac_sha256(key, &value)) {
return Some(value)
}
return None
}
None => return None
}
}
let session = random.token(16)
print(f"{session.len()} characters")
let cookie = sign(&key, &("user=42;session=" + session))
print(f"{verify(&key, &cookie).is_some()}")
let forged = cookie.replace("user=42", "user=1")
print(f"{verify(&key, &forged).is_some()}")
22 characters
true
false