1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-18 21:57:50 +02:00

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

View File

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