pocketbase/tools/security/random.go

30 lines
755 B
Go
Raw Normal View History

2022-07-07 05:19:05 +08:00
package security
import (
"crypto/rand"
)
// RandomString generates a random string with the specified length.
2022-07-07 05:19:05 +08: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.
func RandomStringWithAlphabet(length int, alphabet string) string {
2022-07-07 05:19:05 +08:00
bytes := make([]byte, length)
2022-07-07 05:19:05 +08:00
rand.Read(bytes)
2022-07-07 05:19:05 +08:00
for i, b := range bytes {
bytes[i] = alphabet[b%byte(len(alphabet))]
}
return string(bytes)
}