2021-07-21 23:04:00 +00:00
|
|
|
package random
|
|
|
|
|
|
|
|
import (
|
2021-10-17 20:13:14 +00:00
|
|
|
"crypto/rand"
|
|
|
|
"math/big"
|
2021-07-21 23:04:00 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
Lowercase = "abcdefghijklmnopqrstuvwxyz"
|
|
|
|
Alphabetic = Uppercase + Lowercase
|
|
|
|
Numeric = "0123456789"
|
|
|
|
Alphanumeric = Alphabetic + Numeric
|
|
|
|
Symbols = "`" + `~!@#$%^&*()-_+={}[]|\;:"<>,./?`
|
|
|
|
Hex = Numeric + "abcdef"
|
|
|
|
)
|
|
|
|
|
2021-10-17 20:13:14 +00:00
|
|
|
func Bytes(length int) ([]byte, error) {
|
|
|
|
b := make([]byte, length)
|
2021-07-21 23:04:00 +00:00
|
|
|
|
2021-10-17 20:13:14 +00:00
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return b, nil
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 20:13:14 +00:00
|
|
|
func String(length int, charsets ...string) (string, error) {
|
2021-07-21 23:04:00 +00:00
|
|
|
charset := strings.Join(charsets, "")
|
|
|
|
|
|
|
|
if charset == "" {
|
|
|
|
charset = Alphabetic
|
|
|
|
}
|
|
|
|
|
|
|
|
b := make([]byte, length)
|
|
|
|
|
|
|
|
for i := range b {
|
2021-10-17 20:13:14 +00:00
|
|
|
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
b[i] = charset[n.Int64()]
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 20:13:14 +00:00
|
|
|
return string(b), nil
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|