123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package rsaEncrypt
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "encoding/base64"
- "encoding/pem"
- "errors"
- "fmt"
- "github.com/tidwall/gjson"
- "io/ioutil"
- "net/http"
- )
- // GetPublicKey 获取公钥的函数
- func GetPublicKey(url string) (string, error) {
- resp, err := http.Get(url) // 请替换为实际的获取公钥接口URL
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return "", err
- }
- if gjson.Get(string(body), "code").Int() == 0 {
- s := gjson.Get(string(body), "data.public_key").String()
- return s, nil
- }
- return "", errors.New("未获取到公钥信息")
- }
- // ParseRSAPublicKeyFromPEM 解析公钥
- func ParseRSAPublicKeyFromPEM(pubPEM string) (*rsa.PublicKey, error) {
- block, _ := pem.Decode([]byte(pubPEM))
- if block == nil || block.Type != "PUBLIC KEY" {
- return nil, fmt.Errorf("failed to decode PEM block containing public key")
- }
- pub, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- switch pub := pub.(type) {
- case *rsa.PublicKey:
- return pub, nil
- default:
- return nil, fmt.Errorf("not an RSA key")
- }
- }
- // RsaEncrypt 使用RSA公钥加密
- func RsaEncrypt(publicKey *rsa.PublicKey, plainText []byte) (string, error) {
- encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
- if err != nil {
- return "", err
- }
- return base64.StdEncoding.EncodeToString(encryptedData), nil
- }
- func GetToken(url string, plainText []byte) (string, error) {
- // 获取公钥
- publicKeyPEM, err := GetPublicKey(url)
- if err != nil {
- return "", err
- }
- // 解析公钥
- publicKey, err := ParseRSAPublicKeyFromPEM(publicKeyPEM)
- if err != nil {
- return "", err
- }
- // 加密数据
- encryptedData, err := RsaEncrypt(publicKey, plainText)
- if err != nil {
- return "", err
- }
- return encryptedData, nil
- }
|