Go

Crypto-Random Bytes + Hex/Base64

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`crypto/rand` is the cryptographic CSPRNG. Use it for tokens, session IDs, API keys, password salts — anywhere `math/rand` would be a security bug.
Go
Raw
package main

import (
    "crypto/rand"
    "encoding/base64"
    "encoding/hex"
    "fmt"
)

func randomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    return b, err
}

func RandomHex(n int) string {
    b, _ := randomBytes(n)
    return hex.EncodeToString(b)
}

func RandomURLToken(n int) string {
    b, _ := randomBytes(n)
    return base64.RawURLEncoding.EncodeToString(b)
}

func main() {
    fmt.Println(RandomHex(16))         // 32-char hex string
    fmt.Println(RandomURLToken(32))    // URL-safe ~43-char token
    // ⚠️ NEVER use math/rand for secrets — its sequence is predictable.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.