1.利用工具生成秘钥
2.前端代码 Rsa加密
引入js jsencrypt.js
// 把生成的公钥复制过来
var publicKey = `将生成的公钥粘贴复制过来`
// rsa加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(publicKey);
var encrypted = encrypt.encrypt(password);// encrypted加密后的数据
// 执行提交,将加密后的数据提交到后台
3.后端代码 Rsa解密
3.1已入库
我们引入库的时候,可以使用go get。如果开启了go mod,也可以使用go mod 下载。
go get github.com/smartwalle/crypto4go
3.2思路就是,把我们的密钥key 和要解密的数据data,转换成base64格式的字符串,传入封装好的方法中,会返回解密后的数据。
下面包含了一个完整的例子,复制过去应该就可以执行测试。
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"fmt"
"log"
"strings"
"github.com/smartwalle/crypto4go"
)
func main() {
// 私钥
var privateKey = `将生成的私钥粘贴复制过来`
// 获取前端传来的加密数据
data :=this.getString("data")
aeskey, err := RSADecryptByPrivateKey(data , privateKey )
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(aeskey)//3WZHqust0PBS9z5CBBbQig==
}
func RSADecryptByPrivateKey(data string, privateKey string) (string, error) {
priKey, err := crypto4go.ParsePKCS1PrivateKey(crypto4go.FormatPKCS1PrivateKey(string(privateKey)))
if err != nil {
priKey, err = crypto4go.ParsePKCS8PrivateKey(crypto4go.FormatPKCS8PrivateKey(string(privateKey)))
if err != nil {
fmt.Println("ParsePKCS8PrivateKey : ", err.Error())
return "", err
}
}
// 转成base64
key, err := base64.StdEncoding.DecodeString(data)
if err != nil {
fmt.Println("base64.RawURLEncoding.DecodeString : ", err.Error())
return "", err
}
partLen := priKey.N.BitLen() / 8
chunks := split([]byte(key), partLen)
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, chunk)
if err != nil {
return "", err
}
buffer.Write(decrypted)
}
return buffer.String(), err
}
func split(buf []byte, lim int) [][]byte {
var chunk []byte
chunks := make([][]byte, 0, len(buf)/lim+1)
for len(buf) >= lim {
chunk, buf = buf[:lim], buf[lim:]
chunks = append(chunks, chunk)
}
if len(buf) > 0 {
chunks = append(chunks, buf[:len(buf)])
}
return chunks
}