FAQ - Help and questions

How do I generate random tokens and keys that cannot be guessed?

#security#random#tokenspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Take at least 128 bits, preferably 256, from the operating system's cryptographic random generator, for example with the getrandom crate, and encode them as hex or base64. Never derive a secret from the clock, a counter, a process ID or a general-purpose random function seeded by time.

Checked with rustc 1.93.0, getrandom 0.2.17, hex 0.4.3, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

Cargo.tomltoml
[dependencies]
getrandom = "0.2"
hex = "0.4"
src/main.rsrust
/// 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);
}
text
length: 64
two tokens differ: true

The 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#

  1. Fill a byte array with getrandom::getrandom.
  2. Encode it (hex, or URL-safe base64) so it can travel in a URL or header.
  3. Handle the error instead of using unwrap where you can: if the system cannot provide randomness the program should refuse the request, not use a weaker value.
  4. 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet