Generate secure random bytes in Go using the crypto/rand package's Read function for cryptographic safety.
Use crypto/rand to generate cryptographically secure random numbers by reading from the operating system's entropy source.
package main
import (
"crypto/rand"
"fmt"
)
func main() {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
fmt.Printf("%x\n", b)
}
This code generates 16 random bytes and prints them as a hexadecimal string.
crypto/rand generates random numbers that are unpredictable and safe for security tasks like creating passwords or encryption keys. Unlike standard random functions, it uses your computer's hardware entropy to ensure the numbers cannot be guessed by attackers. Think of it as using a physical dice roll instead of a predictable computer pattern.