Go语言实现与JSEncrypt相同公钥加密:后端加密实战
使用Go语言的crypto/rsa包可以轻松实现与前端JSEncrypt加密相同的公钥加密功能。下面是一个示例代码:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/ioutil"
)
func main() {
// 读取公钥文件
pubKeyBytes, err := ioutil.ReadFile('public.pem')
if err != nil {
fmt.Println('读取公钥文件失败:', err)
return
}
// 解码公钥PEM块
pubPem, _ := pem.Decode(pubKeyBytes)
if pubPem == nil {
fmt.Println('解码公钥PEM块失败')
return
}
// 解析公钥
pubKey, err := x509.ParsePKIXPublicKey(pubPem.Bytes)
if err != nil {
fmt.Println('解析公钥失败:', err)
return
}
// 类型断言为*rsa.PublicKey
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
if !ok {
fmt.Println('类型断言失败')
return
}
// 待加密的数据
plainText := 'Hello, World!'
// 使用公钥加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(plainText))
if err != nil {
fmt.Println('加密失败:', err)
return
}
// Base64编码加密结果
encrypted := base64.StdEncoding.EncodeToString(cipherText)
fmt.Println('加密后的数据:', encrypted)
}
在上面的示例代码中,我们首先读取公钥文件('public.pem'),然后解码公钥PEM块并解析公钥。接下来,我们使用公钥对待加密的数据进行加密,并通过Base64编码将加密结果转换为字符串。最后,我们输出加密后的数据。
请注意,示例代码中的公钥文件('public.pem')应该是包含公钥的PEM格式文件。如果你的公钥不是PEM格式,可以使用crypto/rsa包的其他方法来解析公钥。
原文地址: https://www.cveoy.top/t/topic/pkqs 著作权归作者所有。请勿转载和采集!