1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-01-25 14:43:42 +02:00

65 lines
1.8 KiB
Go
Raw Normal View History

2022-07-07 00:19:05 +03:00
package security
import (
2022-11-06 15:26:34 +02:00
cryptoRand "crypto/rand"
"math/big"
2022-11-06 15:26:34 +02:00
mathRand "math/rand"
2022-11-06 15:30:56 +02:00
"time"
2022-07-07 00:19:05 +03:00
)
2022-11-06 15:26:34 +02:00
const defaultRandomAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
2022-11-06 15:30:56 +02:00
func init() {
mathRand.Seed(time.Now().UnixNano())
}
2022-11-06 15:26:34 +02:00
// RandomString generates a cryptographically random string with the specified length.
2022-07-07 00:19:05 +03:00
//
2022-11-06 15:26:34 +02:00
// The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding.
2022-07-07 00:19:05 +03:00
func RandomString(length int) string {
2022-11-06 15:26:34 +02:00
return RandomStringWithAlphabet(length, defaultRandomAlphabet)
}
// 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 {
2022-11-06 15:26:34 +02:00
n, err := cryptoRand.Int(cryptoRand.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
}
2022-11-06 15:26:34 +02:00
// PseudorandomString generates a pseudorandom string with the specified length.
2022-11-06 15:26:34 +02:00
//
// The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding.
//
2022-11-06 15:35:43 +02:00
// For a cryptographically random string (but a little bit slower) use RandomString instead.
2022-11-06 15:28:41 +02:00
func PseudorandomString(length int) string {
2022-11-06 15:35:43 +02:00
return PseudorandomStringWithAlphabet(length, defaultRandomAlphabet)
2022-11-06 15:26:34 +02:00
}
2022-11-06 15:28:41 +02:00
// PseudorandomStringWithAlphabet generates a pseudorandom string
2022-11-06 15:26:34 +02:00
// with the specified length and characters set.
//
// For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead.
2022-11-06 15:28:41 +02:00
func PseudorandomStringWithAlphabet(length int, alphabet string) string {
2022-11-06 15:26:34 +02:00
b := make([]byte, length)
max := len(alphabet)
for i := range b {
b[i] = alphabet[mathRand.Intn(max)]
}
return string(b)
}