utils.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/rand"
  5. "fmt"
  6. "math/big"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strconv"
  12. )
  13. // VerifyPhone 验证手机号是否正确
  14. func VerifyPhone(phone string) bool {
  15. // 示例:中国大陆手机号(1开头,11位)
  16. reg := regexp.MustCompile(`^1[3-9]\d{9}$`)
  17. return reg.MatchString(phone)
  18. }
  19. // GetFourRandomDigits 获取4位随机数字
  20. func GetFourRandomDigits() string {
  21. // 生成 [0, 8999] 的安全随机数
  22. n, err := rand.Int(rand.Reader, big.NewInt(9000))
  23. if err != nil {
  24. return ""
  25. }
  26. // 转换为 1000~9999 范围
  27. randomNum := n.Int64() + 1000
  28. return strconv.FormatInt(randomNum, 10)
  29. }
  30. // Md5Sign 使用MD5加密
  31. func Md5Sign(str string) string {
  32. data := []byte(str) //切片
  33. has := md5.Sum(data)
  34. md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
  35. return md5str
  36. }
  37. // UrlEncode
  38. func UrlEncode(str string) string {
  39. return url.QueryEscape(str)
  40. }
  41. // LoadPrivateKeyWithPath 通过私钥的文件路径内容加载私钥
  42. func LoadPrivateKeyWithPath(path string) (privateKey string) {
  43. absPath, _ := filepath.Abs(path)
  44. privateKeyBytes, err := os.ReadFile(absPath)
  45. if err != nil {
  46. return ""
  47. }
  48. return string(privateKeyBytes)
  49. }
  50. // LoadPublicKeyWithPath 通过公钥的文件路径加载公钥
  51. func LoadPublicKeyWithPath(path string) (publicKey string) {
  52. absPath, _ := filepath.Abs(path)
  53. publicKeyBytes, err := os.ReadFile(absPath)
  54. if err != nil {
  55. return ""
  56. }
  57. return string(publicKeyBytes)
  58. }