To generate a cryptographically secure random number in Go, you can make use of crypto/rand
package. Here's an example on how to do it:
package main
import (
"crypto/rand"
"encoding/binary"
"fmt"
)
func main() {
// Create a byte slice to hold the random number
numBytes := 8 // 8 bytes = 64 bits
randBytes := make([]byte, numBytes)
// Fill the byte slice with random data
_, err := rand.Read(randBytes)
if err != nil {
fmt.Println("Error generating random number:", err)
return
}
// Convert the byte slice to an integer
randNum := binary.BigEndian.Uint64(randBytes)
// Ensure the random number is positive
if randNum < 0 {
randNum = -randNum
}
// Print the random number
fmt.Println("Random number:", randNum)
}
In this example, we generate a random number with 64 bits (8 bytes) of entropy. The rand.Read()
function is used to fill the byte array with random data. Then, we convert the byte array to an unsigned 64-bit integer using binary.BigEndian.Uint64()
. Finally, we ensure the random number is positive and print it to the console.
Note that crypto/rand
library accesses a system-level random number generator, which provides a cryptographically secure source of randomness.