password.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package gofakeit
  2. import (
  3. "math/rand"
  4. )
  5. const lowerStr = "abcdefghijklmnopqrstuvwxyz"
  6. const upperStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  7. const numericStr = "0123456789"
  8. const specialStr = "!@#$%&*+-=?"
  9. const spaceStr = " "
  10. // Password will generate a random password
  11. // Minimum number length of 5 if less than
  12. func Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string {
  13. // Make sure the num minimun is at least 5
  14. if num < 5 {
  15. num = 5
  16. }
  17. i := 0
  18. b := make([]byte, num)
  19. var passString string
  20. if lower {
  21. passString += lowerStr
  22. b[i] = lowerStr[rand.Int63()%int64(len(lowerStr))]
  23. i++
  24. }
  25. if upper {
  26. passString += upperStr
  27. b[i] = upperStr[rand.Int63()%int64(len(upperStr))]
  28. i++
  29. }
  30. if numeric {
  31. passString += numericStr
  32. b[i] = numericStr[rand.Int63()%int64(len(numericStr))]
  33. i++
  34. }
  35. if special {
  36. passString += specialStr
  37. b[i] = specialStr[rand.Int63()%int64(len(specialStr))]
  38. i++
  39. }
  40. if space {
  41. passString += spaceStr
  42. b[i] = spaceStr[rand.Int63()%int64(len(spaceStr))]
  43. i++
  44. }
  45. // Set default if empty
  46. if passString == "" {
  47. passString = lowerStr + numericStr
  48. }
  49. // Loop through and add it up
  50. for i <= num-1 {
  51. b[i] = passString[rand.Int63()%int64(len(passString))]
  52. i++
  53. }
  54. // Shuffle bytes
  55. for i := range b {
  56. j := rand.Intn(i + 1)
  57. b[i], b[j] = b[j], b[i]
  58. }
  59. return string(b)
  60. }