Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created January 18, 2025 01:22
Show Gist options
  • Save Rican7/eed0b2744fd5823389c43554bb7fbe15 to your computer and use it in GitHub Desktop.
Save Rican7/eed0b2744fd5823389c43554bb7fbe15 to your computer and use it in GitHub Desktop.
Generate a cryptographically secure random digit string in Go, based on Go 1.24's crypto/rand.Text.
package main
import (
"crypto/rand"
)
const numericAlphabet = "0123456789"
const numericAlphaLen = len(numericAlphabet)
// RandomDigits returns a cryptographically secure random digit string of the
// provided length.
func RandomDigits(length uint) string {
src := make([]byte, length)
rand.Read(src)
for i := range src {
src[i] = numericAlphabet[int(src[i])%numericAlphaLen]
}
return string(src)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment