rsa.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package rsaEncrypt
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "errors"
  9. "fmt"
  10. "github.com/tidwall/gjson"
  11. "io/ioutil"
  12. "net/http"
  13. )
  14. // GetPublicKey 获取公钥的函数
  15. func GetPublicKey(url string) (string, error) {
  16. resp, err := http.Get(url) // 请替换为实际的获取公钥接口URL
  17. if err != nil {
  18. return "", err
  19. }
  20. defer resp.Body.Close()
  21. body, err := ioutil.ReadAll(resp.Body)
  22. if err != nil {
  23. return "", err
  24. }
  25. if gjson.Get(string(body), "code").Int() == 0 {
  26. s := gjson.Get(string(body), "data.public_key").String()
  27. return s, nil
  28. }
  29. return "", errors.New("未获取到公钥信息")
  30. }
  31. // ParseRSAPublicKeyFromPEM 解析公钥
  32. func ParseRSAPublicKeyFromPEM(pubPEM string) (*rsa.PublicKey, error) {
  33. block, _ := pem.Decode([]byte(pubPEM))
  34. if block == nil || block.Type != "PUBLIC KEY" {
  35. return nil, fmt.Errorf("failed to decode PEM block containing public key")
  36. }
  37. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  38. if err != nil {
  39. return nil, err
  40. }
  41. switch pub := pub.(type) {
  42. case *rsa.PublicKey:
  43. return pub, nil
  44. default:
  45. return nil, fmt.Errorf("not an RSA key")
  46. }
  47. }
  48. // RsaEncrypt 使用RSA公钥加密
  49. func RsaEncrypt(publicKey *rsa.PublicKey, plainText []byte) (string, error) {
  50. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
  51. if err != nil {
  52. return "", err
  53. }
  54. return base64.StdEncoding.EncodeToString(encryptedData), nil
  55. }
  56. func GetToken(url string, plainText []byte) (string, error) {
  57. // 获取公钥
  58. publicKeyPEM, err := GetPublicKey(url)
  59. if err != nil {
  60. return "", err
  61. }
  62. // 解析公钥
  63. publicKey, err := ParseRSAPublicKeyFromPEM(publicKeyPEM)
  64. if err != nil {
  65. return "", err
  66. }
  67. // 加密数据
  68. encryptedData, err := RsaEncrypt(publicKey, plainText)
  69. if err != nil {
  70. return "", err
  71. }
  72. return encryptedData, nil
  73. }