How to Use crypto/rand for Secure Random Numbers in Go

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.