updated the random generator for more even distribution

This commit is contained in:
Gani Georgiev 2022-11-05 17:55:32 +02:00
parent a2abeb872a
commit 65693d1916
1 changed files with 12 additions and 6 deletions

View File

@ -2,6 +2,7 @@ package security
import ( import (
"crypto/rand" "crypto/rand"
"math/big"
) )
// RandomString generates a random string with the specified length. // RandomString generates a random string with the specified length.
@ -16,14 +17,19 @@ func RandomString(length int) string {
// RandomStringWithAlphabet generates a cryptographically random string // RandomStringWithAlphabet generates a cryptographically random string
// with the specified length and characters set. // with the specified length and characters set.
//
// It panics if for some reason rand.Int returns a non-nil error.
func RandomStringWithAlphabet(length int, alphabet string) string { func RandomStringWithAlphabet(length int, alphabet string) string {
bytes := make([]byte, length) b := make([]byte, length)
max := big.NewInt(int64(len(alphabet)))
rand.Read(bytes) for i := range b {
n, err := rand.Int(rand.Reader, max)
for i, b := range bytes { if err != nil {
bytes[i] = alphabet[b%byte(len(alphabet))] panic(err)
}
b[i] = alphabet[n.Int64()]
} }
return string(bytes) return string(b)
} }