Skip to content

Instantly share code, notes, and snippets.

@Shemeikka
Created August 19, 2015 05:42
Show Gist options
  • Save Shemeikka/04f5fd2bdf5c4c624666 to your computer and use it in GitHub Desktop.
Save Shemeikka/04f5fd2bdf5c4c624666 to your computer and use it in GitHub Desktop.
Generates random n sized hex string
import (
crand "crypto/rand"
"math/big"
)
// Generates random n sized hex string
func RandString(n int) string {
const alphanum = "0123456789ABCDEF"
symbols := big.NewInt(int64(len(alphanum)))
states := big.NewInt(0)
states.Exp(symbols, big.NewInt(int64(n)), nil)
r, err := crand.Int(crand.Reader, states)
if err != nil {
panic(err)
}
var bytes = make([]byte, n)
r2 := big.NewInt(0)
symbol := big.NewInt(0)
for i := range bytes {
r2.DivMod(r, symbols, symbol)
r, r2 = r2, r
bytes[i] = alphanum[symbol.Int64()]
}
return string(bytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment