auth_utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package auth
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "eta/eta_mini_ht_api/common/exception"
  9. stringUtils "eta/eta_mini_ht_api/common/utils/string"
  10. "math/big"
  11. "regexp"
  12. )
  13. const (
  14. letterBytes = "0123456789"
  15. )
  16. func GenerateCode(length int) (string, error) {
  17. if length <= 0 {
  18. return "", exception.New(exception.IllegalCodeLength)
  19. }
  20. b := make([]byte, length)
  21. for i := range b {
  22. n, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
  23. if err != nil {
  24. return "", err
  25. }
  26. b[i] = letterBytes[n.Int64()]
  27. }
  28. return string(b), nil
  29. }
  30. func IsValidMobile(mobile string) bool {
  31. if stringUtils.IsBlank(mobile) {
  32. return false
  33. }
  34. regex := `^(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$`
  35. matched, _ := regexp.MatchString(regex, mobile)
  36. return matched
  37. }
  38. func DesBase64Encrypt(origData []byte, desKey string) []byte {
  39. result, err := tripleDesEncrypt(origData, []byte(desKey))
  40. if err != nil {
  41. panic(any(err))
  42. }
  43. return []byte(base64.StdEncoding.EncodeToString(result))
  44. }
  45. // 3DES加密
  46. func tripleDesEncrypt(origData, key []byte) ([]byte, error) {
  47. block, err := des.NewTripleDESCipher(key)
  48. if err != nil {
  49. return nil, err
  50. }
  51. origData = pKCS5Padding(origData, block.BlockSize())
  52. // origData = ZeroPadding(origData, block.BlockSize())
  53. blockMode := cipher.NewCBCEncrypter(block, key[:8])
  54. crypted := make([]byte, len(origData))
  55. blockMode.CryptBlocks(crypted, origData)
  56. return crypted, nil
  57. }
  58. func pKCS5Padding(ciphertext []byte, blockSize int) []byte {
  59. padding := blockSize - len(ciphertext)%blockSize
  60. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  61. return append(ciphertext, padtext...)
  62. }