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.

141 lines
3.7KB

  1. package utils
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/aes"
  6. "crypto/cipher"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/sha256"
  10. "crypto/x509"
  11. "encoding/base64"
  12. "fmt"
  13. "github.com/tal-tech/go-zero/core/logx"
  14. "math"
  15. "math/big"
  16. r "math/rand"
  17. "time"
  18. )
  19. // RSAEncrypt RSA加密
  20. // plainText 要加密的数据
  21. // publicKey 公钥匙内容
  22. func RSAEncrypt(plainText []byte, publicKey string) (string, error) {
  23. key, _ := base64.StdEncoding.DecodeString(publicKey)
  24. pubKey, _ := x509.ParsePKIXPublicKey(key)
  25. logx.Infof("%v", pubKey)
  26. //解密pem格式的公钥
  27. //block, _ := pem.Decode([]byte(publicKey))
  28. //if block == nil {
  29. // return "", fmt.Errorf("public key error")
  30. //}
  31. //// 解析公钥
  32. //pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  33. //if err != nil {
  34. // return "", err
  35. //}
  36. // 类型断言
  37. pub := pubKey.(*rsa.PublicKey)
  38. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plainText)
  39. return base64.StdEncoding.EncodeToString(encryptedData), err
  40. }
  41. // RSADecrypt RSA解密
  42. // cipherText 需要解密的byte数据
  43. // privateKey 私钥匙内容
  44. func RSADecrypt(cipherText, privateKey string) (string, error) {
  45. encryptedDecodeBytes, err := base64.StdEncoding.DecodeString(cipherText)
  46. if err != nil {
  47. return "", err
  48. }
  49. key, _ := base64.StdEncoding.DecodeString(privateKey)
  50. prvKey, _ := x509.ParsePKCS1PrivateKey(key)
  51. originalData, err := rsa.DecryptPKCS1v15(rand.Reader, prvKey, encryptedDecodeBytes)
  52. return string(originalData), err
  53. }
  54. func RSAPriEncrypt(cipherText, privateKey string) (string, error) {
  55. key, _ := base64.StdEncoding.DecodeString(privateKey)
  56. prvKey, _ := x509.ParsePKCS1PrivateKey(key)
  57. rng := rand.Reader
  58. hashed := sha256.Sum256([]byte(cipherText))
  59. signature, err := rsa.SignPKCS1v15(rng, prvKey, crypto.SHA256, hashed[:])
  60. if err != nil {
  61. logx.Errorf("Error from signing: %s\n", err)
  62. return "", err
  63. }
  64. return fmt.Sprintf("%x", signature), nil
  65. }
  66. //RangeRand 生成区间[-m, n]的安全随机数
  67. func RangeRand(min, max int64) string {
  68. if min > max {
  69. panic("the min is greater than max!")
  70. }
  71. if min < 0 {
  72. f64Min := math.Abs(float64(min))
  73. i64Min := int64(f64Min)
  74. result, _ := rand.Int(rand.Reader, big.NewInt(max+1+i64Min))
  75. return fmt.Sprintf("%d", result.Int64()-i64Min)
  76. } else {
  77. result, _ := rand.Int(rand.Reader, big.NewInt(max-min+1))
  78. return fmt.Sprintf("%d", min+result.Int64())
  79. }
  80. }
  81. // Krand 随机字符串
  82. func Krand(size int, kind int) []byte {
  83. ikind, kinds, result := kind, [][]int{{10, 48}, {26, 97}, {26, 65}}, make([]byte, size)
  84. is_all := kind > 2 || kind < 0
  85. r.Seed(time.Now().UnixNano())
  86. for i := 0; i < size; i++ {
  87. if is_all { // random ikind
  88. ikind = r.Intn(3)
  89. }
  90. scope, base := kinds[ikind][0], kinds[ikind][1]
  91. result[i] = uint8(base + r.Intn(scope))
  92. }
  93. return result
  94. }
  95. //AESEncrypt AES加密
  96. func AESEncrypt(origData, key, iv []byte) (string, error) {
  97. block, err := aes.NewCipher(key)
  98. if err != nil {
  99. return "", err
  100. }
  101. blockSize := block.BlockSize()
  102. origData = PKCS5Padding(origData, blockSize)
  103. blockMode := cipher.NewCFBEncrypter(block, iv)
  104. crypted := make([]byte, len(origData))
  105. blockMode.XORKeyStream(crypted, origData)
  106. return base64.StdEncoding.EncodeToString(crypted), nil
  107. }
  108. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  109. padding := blockSize - len(ciphertext)%blockSize
  110. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  111. return append(ciphertext, padtext...)
  112. }
  113. /**
  114. * 计算sha256值
  115. *
  116. * @param paramMap
  117. * @return 签名后的所有数据,原始数据+签名
  118. */
  119. func Sha256(requestMap map[string]string) string {
  120. str := ""
  121. for k, v := range requestMap {
  122. str += fmt.Sprintf("%s=%s&", k, v)
  123. }
  124. logx.Infof("requestMap %s", str)
  125. sum := sha256.Sum256([]byte(str))
  126. return fmt.Sprintf("%x", sum)
  127. }