StringCharset generates a random string using the provided charset and size.
(charSetStr string, size int)
| 69 | |
| 70 | // StringCharset generates a random string using the provided charset and size. |
| 71 | func StringCharset(charSetStr string, size int) (string, error) { |
| 72 | if size == 0 { |
| 73 | return "", nil |
| 74 | } |
| 75 | |
| 76 | if len(charSetStr) == 0 { |
| 77 | return "", xerrors.Errorf("charSetStr must not be empty") |
| 78 | } |
| 79 | |
| 80 | charSet := []rune(charSetStr) |
| 81 | |
| 82 | // We pre-allocate the entropy to amortize the crypto/rand syscall overhead. |
| 83 | entropy := make([]byte, 4*size) |
| 84 | |
| 85 | _, err := rand.Read(entropy) |
| 86 | if err != nil { |
| 87 | return "", err |
| 88 | } |
| 89 | |
| 90 | var buf strings.Builder |
| 91 | buf.Grow(size) |
| 92 | |
| 93 | for i := 0; i < size; i++ { |
| 94 | r := binary.BigEndian.Uint32(entropy[:4]) |
| 95 | entropy = entropy[4:] |
| 96 | |
| 97 | ci, err := unbiasedModulo32( |
| 98 | r, |
| 99 | int32(len(charSet)), // #nosec G115 - Safe conversion as len(charSet) will be reasonably small for character sets |
| 100 | ) |
| 101 | if err != nil { |
| 102 | return "", err |
| 103 | } |
| 104 | |
| 105 | _, _ = buf.WriteRune(charSet[ci]) |
| 106 | } |
| 107 | |
| 108 | return buf.String(), nil |
| 109 | } |
| 110 | |
| 111 | // String returns a random string using Default. |
| 112 | func String(size int) (string, error) { |