go / intermediate
Snippet
Cryptographically Secure Random Data Generation
For security-sensitive tasks like generating session IDs, password reset tokens, or API keys, Go's standard library provides the crypto/rand package. Unlike math/rand which is pseudo-random and predictable, crypto/rand interfaces with the operating system's cryptographically secure pseudorandom number generator (CSPRNG). It fills a byte slice with random bytes that can then be encoded into a hex string.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package mainimport ("crypto/rand""encoding/hex""fmt")func generateSecureToken(length int) (string, error) {bytes := make([]byte, length)_, err := rand.Read(bytes)if err != nil {return "", err}return hex.EncodeToString(bytes), nil}func main() {token, err := generateSecureToken(16)if err != nil {fmt.Println("Error:", err)return}fmt.Println("Secure Token:", token)}
Breakdown
1
bytes := make([]byte, length)
Allocates a byte slice of the specified length to hold the random data.
2
_, err := rand.Read(bytes)
Reads cryptographically secure random bytes from the OS entropy pool into the slice.
3
if err != nil { return "", err }
Checks for errors, which might occur if the system runs out of entropy or fails to read.
4
hex.EncodeToString(bytes)
Converts the raw random bytes into a readable, hexadecimal string representation.