0 day streak
go / intermediate
Snippet

Generating Secure Cryptographic Tokens with Crypto Rand

For security-sensitive tasks like generating session tokens or API keys, `crypto/rand` must be used instead of `math/rand`. It interfaces with the operating system's secure entropy generator.

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
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
func generateSecureToken(length int) (string, error) {
bytes := make([]byte, length)
if _, err := rand.Read(bytes); 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 desired length to hold the random data.
2
if _, err := rand.Read(bytes); err != nil {
Fills the byte slice with cryptographically secure random bytes from the OS entropy source.
3
return hex.EncodeToString(bytes), nil
Encodes the secure raw bytes into a readable hexadecimal string representation.