Debian Codegraph @

crypto/randutil/random.go

raw symbols SCIP
1 package randutil
2
3 import (
4 "crypto/rand"
5 "io"
6 "math/big"
7
8 "github.com/pkg/errors"
9 )
10
11 var ascii string
12
13 func init() {
14 // initialize the charcters in ascii
15 aciiBytes := make([]byte, 94)
16 for i := range aciiBytes {
17 aciiBytes[i] = byte(i + 33)
18 }
19 ascii = string(aciiBytes)
20 }
21
22 // Salt generates a new random salt of the given size.
23 func Salt(size int) ([]byte, error) {
24 salt := make([]byte, size)
25 _, err := io.ReadFull(rand.Reader, salt)
26 if err != nil {
27 return nil, errors.Wrap(err, "error generating salt")
28 }
29 return salt, nil
30 }
31
32 // String returns a random string of a given length using the characters in
33 // the given string. It splits the string on runes to support UTF-8
34 // characters.
35 func String(length int, chars string) (string, error) {
36 result := make([]rune, length)
37 runes := []rune(chars)
38 x := int64(len(runes))
39 for i := range result {
40 num, err := rand.Int(rand.Reader, big.NewInt(x))
41 if err != nil {
42 return "", errors.Wrap(err, "error creating random number")
43 }
44 result[i] = runes[num.Int64()]
45 }
46 return string(result), nil
47 }
48
49 // Hex returns a random string of the given length using the hexadecimal
50 // characters in lower case (0-9+a-f).
51 func Hex(length int) (string, error) {
52 return String(length, "0123456789abcdef")
53 }
54
55 // Alphanumeric returns a random string of the given length using the 62
56 // alphanumeric characters in the POSIX/C locale (a-z+A-Z+0-9).
57 func Alphanumeric(length int) (string, error) {
58 return String(length, "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
59 }
60
61 // ASCII returns a securely generated random ASCII string. It reads random
62 // numbers from crypto/rand and searches for printable characters. It will
63 // return an error if the system's secure random number generator fails to
64 // function correctly, in which case the caller must not continue.
65 func ASCII(length int) (string, error) {
66 return String(length, ascii)
67 }