About random token generator
A token is a random value used to identify a session, reset a password or authorise a request. It must be unpredictable.
Good practice
- Use at least 128 bits of randomness; 256 bits is better.
- Make tokens single-use or time-limited where possible.
- Store only a hash of the token on the server.
A worked example
A 32-byte token is 64 hex characters or 43 Base64URL characters and carries 256 bits of randomness. It is suitable for session identifiers, password reset links and API tokens.
Handling tokens
- Send them only over HTTPS.
- Set an expiry and invalidate tokens after use where possible.
- Store a hash on the server, so a database leak does not expose live tokens.
Length and encoding
Hex gives two characters per byte and is easy to read, while Base64URL is shorter for the same strength and safe inside URLs. Pick whichever the receiving system expects.
