2020-01-06 14:32:15 +01:00
|
|
|
package rnd
|
2019-11-08 06:53:40 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2023-12-12 18:42:50 +01:00
|
|
|
"math/big"
|
2019-11-08 06:53:40 +01:00
|
|
|
)
|
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
const CharsetBase36 = "abcdefghijklmnopqrstuvwxyz0123456789"
|
|
|
|
const CharsetBase62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
2019-12-27 05:18:52 +01:00
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
// Base36 generates a random token containing lowercase letters and numbers.
|
|
|
|
func Base36(length int) string {
|
|
|
|
return Charset(length, CharsetBase36)
|
|
|
|
}
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
// Base62 generates a random token containing upper and lower case letters as well as numbers.
|
|
|
|
func Base62(length int) string {
|
|
|
|
return Charset(length, CharsetBase62)
|
|
|
|
}
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
// Charset generates a random token with the specified length and charset.
|
|
|
|
func Charset(length int, charset string) string {
|
|
|
|
if length < 1 {
|
|
|
|
return ""
|
|
|
|
} else if length > 4096 {
|
|
|
|
length = 4096
|
|
|
|
}
|
2019-12-27 05:18:52 +01:00
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
m := big.NewInt(int64(len(charset)))
|
|
|
|
b := make([]byte, length)
|
2019-12-27 05:18:52 +01:00
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
for i := range b {
|
|
|
|
if r, err := rand.Int(rand.Reader, m); err == nil {
|
|
|
|
b[i] = charset[r.Int64()]
|
|
|
|
}
|
2019-12-27 05:18:52 +01:00
|
|
|
}
|
|
|
|
|
2023-12-12 18:42:50 +01:00
|
|
|
return string(b)
|
2019-12-27 05:18:52 +01:00
|
|
|
}
|