Answer#
A token that protects something (a session ID, a password-reset link, an API key, a CSRF token) must be unguessable. That means random bytes from a cryptographically secure generator, and enough of them. The operating system provides one, and the getrandom crate calls it on every platform.
[dependencies]
getrandom = "0.2"
hex = "0.4"/// 32 random bytes from the operating system's generator, as 64 hex characters.
fn new_token() -> Result<String, getrandom::Error> {
let mut bytes = [0u8; 32];
getrandom::getrandom(&mut bytes)?;
Ok(hex::encode(bytes))
}
fn main() {
let a = new_token().expect("the OS random generator failed");
let b = new_token().expect("the OS random generator failed");
println!("length: {}", a.len());
println!("two tokens differ: {}", a != b);
}length: 64
two tokens differ: trueThe program prints the length and a comparison, never the tokens. 32 bytes is 256 bits, written as 64 hex characters. Use URL-safe base64 without padding when you want a shorter string for a cookie.
How to do it#
- Fill a byte array with
getrandom::getrandom. - Encode it (hex, or URL-safe base64) so it can travel in a URL or header.
- Handle the error instead of using
unwrapwhere you can: if the system cannot provide randomness the program should refuse the request, not use a weaker value. - Store only what you must. For tokens the server needs to look up later, store a hash (see the thread on session IDs).
Common mistakes#
- Seeding a simple generator with the time, or using a counter or user ID "plus something". Those are guessable.
- Truncating a token to make it "nicer". Fewer bits means easier guessing.
- Using a UUID for secrets without checking its version. Some versions are built from the time, not from random bits; use random bytes directly.
- Comparing tokens with
==; see the thread on constant-time comparison.
Related questions#
Is the rand crate good enough?#
Read the documentation of the version you use: its default generator is documented as cryptographically secure and is seeded from the operating system. Calling the operating system's generator directly through getrandom is simply the easier thing to reason about for secrets.
How long should a token be?#
The OWASP session guidance asks for at least 64 bits of entropy for session IDs, and the examples here use 256 bits, which leaves a wide margin at a small cost.
Sources#
getrandomdocumentation: https://docs.rs/getrandom/0.2.17/getrandom/- OWASP Session Management Cheat Sheet, "Session ID Properties": https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html