1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-02-04 02:04:08 +02:00

36 lines
902 B
Go
Raw Normal View History

2022-07-07 00:19:05 +03:00
package security
import (
"crypto/rand"
"math/big"
2022-07-07 00:19:05 +03:00
)
// RandomString generates a random string with the specified length.
2022-07-07 00:19:05 +03:00
//
// The generated string is cryptographically random and matches
// [A-Za-z0-9]+ (aka. it's transparent to URL-encoding).
func RandomString(length int) string {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return RandomStringWithAlphabet(length, alphabet)
}
// 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 {
b := make([]byte, length)
max := big.NewInt(int64(len(alphabet)))
for i := range b {
n, err := rand.Int(rand.Reader, max)
if err != nil {
panic(err)
}
b[i] = alphabet[n.Int64()]
2022-07-07 00:19:05 +03:00
}
return string(b)
2022-07-07 00:19:05 +03:00
}