1
0

security.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package pkg
  2. import (
  3. "encoding/hex"
  4. "math/rand"
  5. "golang.org/x/crypto/scrypt"
  6. )
  7. const (
  8. symbol = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~"
  9. letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  10. figure = "0123456789"
  11. )
  12. func generateRandString(length int, s string) string {
  13. var chars = []byte(s)
  14. clen := len(chars)
  15. if clen < 2 || clen > 256 {
  16. panic("Wrong charset length for NewLenChars()")
  17. }
  18. maxrb := 255 - (256 % clen)
  19. b := make([]byte, length)
  20. r := make([]byte, length+(length/4)) // storage for random bytes.
  21. i := 0
  22. for {
  23. if _, err := rand.Read(r); err != nil {
  24. panic("Error reading random bytes: " + err.Error())
  25. }
  26. for _, rb := range r {
  27. c := int(rb)
  28. if c > maxrb {
  29. continue // Skip this number to avoid modulo bias.
  30. }
  31. b[i] = chars[c%clen]
  32. i++
  33. if i == length {
  34. return string(b)
  35. }
  36. }
  37. }
  38. }
  39. // GenerateRandomKey20 生成20位随机字符串
  40. func GenerateRandomKey20() string {
  41. return generateRandString(20, symbol)
  42. }
  43. // GenerateRandomKey16 生成16为随机字符串
  44. func GenerateRandomKey16() string {
  45. return generateRandString(16, symbol)
  46. }
  47. // GenerateRandomKey6 生成6为随机字符串
  48. func GenerateRandomKey6() string {
  49. return generateRandString(6, letter)
  50. }
  51. // GenerateRandomFigureKey6 生成6为随机数字字符串
  52. func GenerateRandomFigureKey6() string {
  53. return generateRandString(6, figure)
  54. }
  55. // SetPassword 根据明文密码和加盐值生成密码
  56. func SetPassword(password string, salt string) (verify string, err error) {
  57. var rb []byte
  58. rb, err = scrypt.Key([]byte(password), []byte(salt), 16384, 8, 1, 32)
  59. if err != nil {
  60. return
  61. }
  62. verify = hex.EncodeToString(rb)
  63. return
  64. }