(length uint8, charsets ...string)
| 43 | } |
| 44 | |
| 45 | func (r *Random) String(length uint8, charsets ...string) string { |
| 46 | charset := strings.Join(charsets, "") |
| 47 | if charset == "" { |
| 48 | charset = Alphanumeric |
| 49 | } |
| 50 | |
| 51 | charsetLen := len(charset) |
| 52 | if charsetLen > 255 { |
| 53 | charsetLen = 255 |
| 54 | } |
| 55 | maxByte := 255 - (256 % charsetLen) |
| 56 | |
| 57 | reader := r.readerPool.Get().(*bufio.Reader) |
| 58 | defer r.readerPool.Put(reader) |
| 59 | |
| 60 | b := make([]byte, length) |
| 61 | rs := make([]byte, length+(length/4)) // perf: avoid read from rand.Reader many times |
| 62 | var i uint8 = 0 |
| 63 | |
| 64 | // security note: |
| 65 | // we can't just simply do b[i]=charset[rb%byte(charsetLen)], |
| 66 | // for example, when charsetLen is 52, and rb is [0, 255], 256 = 52 * 4 + 48. |
| 67 | // this will make the first 48 characters more possibly to be generated then others. |
| 68 | // so we have to skip bytes when rb > maxByte |
| 69 | |
| 70 | for { |
| 71 | _, err := io.ReadFull(reader, rs) |
| 72 | if err != nil { |
| 73 | panic("unexpected error happened when reading from bufio.NewReader(crypto/rand.Reader)") |
| 74 | } |
| 75 | for _, rb := range rs { |
| 76 | if rb > byte(maxByte) { |
| 77 | // Skip this number to avoid bias. |
| 78 | continue |
| 79 | } |
| 80 | b[i] = charset[rb%byte(charsetLen)] |
| 81 | i++ |
| 82 | if i == length { |
| 83 | return string(b) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func String(length uint8, charsets ...string) string { |
| 90 | return global.String(length, charsets...) |
no outgoing calls