Distinguish pseudorandom and cryptographic randomness
Distinguish pseudorandom and cryptographic randomness
Pseudorandom generators produce a deterministic sequence from their initial state, useful for simulations and reproducible tests. A predictable seed is not suitable for secrets. Use crypto/rand for cryptographically secure randomness. Here prand and crand are import aliases for math/rand and crypto/rand.
package main
import ( "fmt" prand "math/rand")
func main() { a := prand.New(prand.NewSource(42)) b := prand.New(prand.NewSource(42)) fmt.Println(a.Intn(100) == b.Intn(100)) fmt.Println(a.Intn(100) == b.Intn(100))}Two separate generators seeded identically return the same sequence when called in the same order. Intn(n) returns zero up to but excluding positive n. This uses the legacy math/rand API for reproducibility, not secret generation.
Expected output:
truetrueUse a cryptographic source
package main
import ( crand "crypto/rand" "fmt" "math/big")
func main() { n, err := crand.Int(crand.Reader, big.NewInt(100)) if err != nil { panic(err) } fmt.Println(n.Sign() >= 0 && n.Cmp(big.NewInt(100)) < 0)}Int draws a uniform value below a positive bound using the supplied random reader. Handle the error and test the range rather than a specific random result. This is not a statistical test or proof of entropy quality. Do not substitute a predictable reader for secrets.
Expected output:
trueTry it locally
Generate 16 bytes with crypto/rand.Read; handle errors and print the byte count, not the bytes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 06: Distinguish pseudorandom and cryptographic randomness
Check the lesson objective before moving on.
Which source is appropriate for secret random bytes?
What should a test of crypto/rand.Int assert here?