The crypto/rand package in Go implements the cryptographically secure random numbers. There are three functions in this package in total that we are going to cover here in this post.
Required imports
To use this package we will import it and also import the math/big package for big numbers that will be used in the int method.
import (
"crypto/rand"
"math/big"
)
The rand.Int() method
This function returns a random value inside the range of [0, upper_bound). Here is an example that generates 5 integers that are in the range of [0,1000).
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
func main() {
for i := 0; i < 5; i++ {
v, e := rand.Int(rand.Reader, big.NewInt(1000))
if e != nil {
fmt.Print(e)
}
fmt.Print(v, " ") // 360 389 174 274 846
}
}
This function is good for generating cryptographically secure random numbers in a range.
The rand.Prime() method
This function generates a prime number of the size provided. Here is an example.
package main
import (
"crypto/rand"
"fmt"
)
func main() {
v, e := rand.Prime(rand.Reader, 1024) // 1024 bit prime
if e != nil {
fmt.Print(e)
}
fmt.Print(v)
}
And the output becomes a 1024-bit prime, which was expected.
The rand.Read() method
This function is a helper function which is simply a read method. In this example it takes 10 secure random numbers and fills the byte slice with it.
package main
import (
"crypto/rand"
"fmt"
)
func main() {
c := 10
b := make([]byte, c)
_, err := rand.Read(b)
CheckError(err)
fmt.Println(b) // [193 174 178 8 109 249 203 255 176 153]
}
func CheckError(e error) {
if e != nil {
fmt.Println(e)
}
}
These are the three methods available in the package. It contains the most essential functions for generating cryptographically secure random numbers. This package can be used whenever we are going to use some sort of cryptographical algorithms and need random numbers.