2022-07-07 00:19:05 +03:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2022-11-05 17:55:32 +02:00
|
|
|
"math/big"
|
2022-07-07 00:19:05 +03:00
|
|
|
)
|
|
|
|
|
2022-08-14 19:30:45 +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"
|
|
|
|
|
2022-08-14 19:30:45 +03:00
|
|
|
return RandomStringWithAlphabet(length, alphabet)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RandomStringWithAlphabet generates a cryptographically random string
|
|
|
|
// with the specified length and characters set.
|
2022-11-05 17:55:32 +02:00
|
|
|
//
|
|
|
|
// It panics if for some reason rand.Int returns a non-nil error.
|
2022-08-14 19:30:45 +03:00
|
|
|
func RandomStringWithAlphabet(length int, alphabet string) string {
|
2022-11-05 17:55:32 +02:00
|
|
|
b := make([]byte, length)
|
|
|
|
max := big.NewInt(int64(len(alphabet)))
|
2022-08-14 19:30:45 +03:00
|
|
|
|
2022-11-05 17:55:32 +02:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-11-05 17:55:32 +02:00
|
|
|
return string(b)
|
2022-07-07 00:19:05 +03:00
|
|
|
}
|