Crypto-Secure Random Tokens
Generate URL-safe tokens from crypto/rand with an entropy floor, plus unbiased numeric codes using crypto/rand.Int.
Code
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"math/big"
)
func RandomToken(size int) (string, error) {
if size < 16 {
return "", fmt.Errorf("token entropy too low: %d bytes", size)
}
buffer := make([]byte, size)
if _, err := rand.Read(buffer); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(buffer), nil
}
func RandomDigits(length int) (string, error) {
if length < 1 {
return "", fmt.Errorf("length must be positive: %d", length)
}
limit := big.NewInt(10)
out := make([]byte, length)
for index := range out {
digit, err := rand.Int(rand.Reader, limit)
if err != nil {
return "", err
}
out[index] = byte('0' + digit.Int64())
}
return string(out), nil
}
func main() {
token, tokenErr := RandomToken(24)
fmt.Println(token, tokenErr)
code, codeErr := RandomDigits(6)
fmt.Println(code, codeErr)
}
How it works
Crypto-Secure Random Tokens is built around the functions RandomToken, RandomDigits and main.
Repetition is confined to for index := range out — the rest of the file is straight-line. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
- Failure is a return value (
error), which keeps control flow explicit at every call site.
Applying it
Entry signature: func RandomToken(size int) (string, error)
The sequence RandomToken and RandomDigits lives in main; running the file triggers it.
Statements that matter
return "", fmt.Errorf("token entropy too low: %d bytes", size)
return "", fmt.Errorf("length must be positive: %d", length)
for index := range out {
digit, err := rand.Int(rand.Reader, limit)
if err != nil {
return "", err
}
out[index] = byte('0' + digit.Int64())
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- What happens when a call fails?
- By return value: each fallible call hands back an `error`, checked at 2 places here.
- How do you run Crypto-Secure Random Tokens?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.