You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.0 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package rand
  2. import (
  3. mrand "math/rand"
  4. )
  5. const (
  6. strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters
  7. )
  8. // Str constructs a random alphanumeric string of given length
  9. // from math/rand's global default Source.
  10. func Str(length int) string {
  11. if length <= 0 {
  12. return ""
  13. }
  14. chars := make([]byte, 0, length)
  15. for {
  16. // nolint:gosec // G404: Use of weak random number generator
  17. val := mrand.Int63()
  18. for i := 0; i < 10; i++ {
  19. v := int(val & 0x3f) // rightmost 6 bits
  20. if v >= 62 { // only 62 characters in strChars
  21. val >>= 6
  22. continue
  23. } else {
  24. chars = append(chars, strChars[v])
  25. if len(chars) == length {
  26. return string(chars)
  27. }
  28. val >>= 6
  29. }
  30. }
  31. }
  32. }
  33. // Bytes returns n random bytes generated from math/rand's global default Source.
  34. func Bytes(n int) []byte {
  35. bs := make([]byte, n)
  36. for i := 0; i < len(bs); i++ {
  37. // nolint:gosec // G404: Use of weak random number generator
  38. bs[i] = byte(mrand.Int() & 0xFF)
  39. }
  40. return bs
  41. }