-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrand.go
36 lines (28 loc) · 856 Bytes
/
crand.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package crand
import (
"crypto/rand"
"golang.org/x/xerrors"
"math/big"
)
const (
Charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
)
// String generates a crypto secure random string of length size using the default charset.
func String(size int) (string, error) {
return generate(size, Charset)
}
// StringWithCharset generates a crypto secure random string of length size using the specified charset.
func StringWithCharset(size int, charset string) (string, error) {
return generate(size, charset)
}
func generate(size int, charset string) (string, error) {
b := make([]byte, size)
for i := 0; i < size; i++ {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
if err != nil {
return "", xerrors.Errorf("generate string: %w", err)
}
b[i] = charset[n.Int64()]
}
return string(b), nil
}