-
how to generate random numbers. This functionality is provided by the math/rand package. The random numbers generated by math/rand are considered cryptographically insecure because the sequences are repeatable with given seed.
-
To generate cryptographically secure numbers, the crypto/rand package should be used. These sequences are not repeatable.
package main
import (
crypto "crypto/rand"
"fmt"
"math/big"
"math/rand"
)
func main() {
sec1 := rand.New(rand.NewSource(10))
sec2 := rand.New(rand.NewSource(10))
for i := 0; i < 5; i++ {
rnd1 := sec1.Int()
rnd2 := sec2.Int()
if rnd1 != rnd2 {
fmt.Println("Rand generated non-equal sequence")
break
} else {
fmt.Printf("Math/Rand1: %d , Math/Rand2: %d\n", rnd1, rnd2)
}
}
for i := 0; i < 5; i++ {
safeNum := NewCryptoRand()
safeNum2 := NewCryptoRand()
if safeNum == safeNum2 {
fmt.Println("Crypto generated equal numbers")
break
} else {
fmt.Printf("Crypto/Rand1: %d , Crypto/Rand2: %d\n",
safeNum, safeNum2)
}
}
}
func NewCryptoRand() int64 {
safeNum, err := crypto.Int(crypto.Reader, big.NewInt(100234))
if err != nil {
panic(err)
}
return safeNum.Int64()
}
output:
sangam:golang-daily sangam$ go run rand.go
Math/Rand1: 1512982403 , Math/Rand2: 1512982403
Math/Rand1: 938371728 , Math/Rand2: 938371728
Math/Rand1: 1727441275 , Math/Rand2: 1727441275
Math/Rand1: 492959835 , Math/Rand2: 492959835
Math/Rand1: 1031730807 , Math/Rand2: 1031730807
Crypto/Rand1: 1156 , Crypto/Rand2: 75947
Crypto/Rand1: 69204 , Crypto/Rand2: 426
Crypto/Rand1: 14141 , Crypto/Rand2: 57210
Crypto/Rand1: 62348 , Crypto/Rand2: 85520
Crypto/Rand1: 77442 , Crypto/Rand2: 91391
-
The previous code presents two possibilities on how to generate random numbers. The first option uses the math/rand package, which is cryptographically insecure, and allows us to generate the same sequence with the use of Source with the same seed number. This approach is usually used in tests. The reason for doing so is for the reproducibility of the sequence.
-
The second option, the cryptographically secure one, is the use of the crypto/rand package. The API uses the Reader to provide the instance of a cryptographically strong pseudo-random generator. The package itself has the default Reader which is usually based on the system-based random number generator.