How to Generate Random Numbers and Bytes in Go (crypto/rand)

Generate secure random bytes and integers in Go using the crypto/rand package for cryptographic safety.

Use crypto/rand to generate cryptographically secure random numbers and bytes, as math/rand is not secure for security-sensitive applications. Read directly into a byte slice or use helper functions like Int to generate random integers within a range.

package main

import (
	"crypto/rand"
	"fmt"
	"math/big"
)

func main() {
	// Generate 16 random bytes
	b := make([]byte, 16)
	_, err := rand.Read(b)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Random bytes: %x\n", b)

	// Generate random integer between 0 and 100
	n, err := rand.Int(rand.Reader, big.NewInt(101))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Random int: %d\n", n)
}