Home > Article > Backend Development > How to Generate Secure Random Integers and Tokens Using 'crypto/rand'?
Random Int Generation using "crypto/rand.Int"
Within the "crypto/rand" package lies the necessity to generate secure random integers. An example of how to achieve this between the range of 0 to 27 is below:
package main import ( "crypto/rand" "fmt" "math/big" ) func main() { nBig, err := rand.Int(rand.Reader, big.NewInt(27)) if err != nil { panic(err) } n := nBig.Int64() fmt.Printf("Random int in [0,27): %d\n", n) }
This function utilizes the "rand.Reader" and the "big.Int" type from "math/big" library to achieve cryptographic randomness beyond the int range.
Secure Token Generation
However, in the context of generating secure tokens, an alternative and more appropriate approach is recommended:
package main import ( "crypto/rand" "encoding/base32" "fmt" ) func main() { token := getToken(10) fmt.Printf("Secure token: %s\n", token) } func getToken(length int) string { randomBytes := make([]byte, 32) _, err := rand.Read(randomBytes) if err != nil { panic(err) } return base32.StdEncoding.EncodeToString(randomBytes)[:length] }
In this scenario, random bytes are generated, then encoded using "base32" to create a token. This approach is deemed sufficient for secure token generation.
The above is the detailed content of How to Generate Secure Random Integers and Tokens Using 'crypto/rand'?. For more information, please follow other related articles on the PHP Chinese website!