1 Star 0 Fork 0

eden-w2w/wechatpay-go

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
rsa_crypto.go 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
EmmetZC 提交于 2021-07-13 21:02 +08:00 . license: add copyright heading
// Copyright 2021 Tencent Inc. All rights reserved.
package utils
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"fmt"
)
// EncryptOAEPWithPublicKey 使用公钥进行加密
func EncryptOAEPWithPublicKey(message string, publicKey *rsa.PublicKey) (ciphertext string, err error) {
if publicKey == nil {
return "", fmt.Errorf("you should input *rsa.PublicKey")
}
ciphertextByte, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, []byte(message), nil)
if err != nil {
return "", fmt.Errorf("encrypt message with public key err:%s", err.Error())
}
ciphertext = base64.StdEncoding.EncodeToString(ciphertextByte)
return ciphertext, nil
}
// EncryptOAEPWithCertificate 先解析出证书中的公钥,然后使用公钥进行加密
func EncryptOAEPWithCertificate(message string, certificate *x509.Certificate) (ciphertext string, err error) {
if certificate == nil {
return "", fmt.Errorf("you should input *x509.Certificate")
}
publicKey, ok := certificate.PublicKey.(*rsa.PublicKey)
if !ok {
return "", fmt.Errorf("certificate is invalid")
}
return EncryptOAEPWithPublicKey(message, publicKey)
}
// DecryptOAEP 使用私钥进行解密
func DecryptOAEP(ciphertext string, privateKey *rsa.PrivateKey) (message string, err error) {
if privateKey == nil {
return "", fmt.Errorf("you should input *rsa.PrivateKey")
}
decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", fmt.Errorf("base64 decode failed, error=%s", err.Error())
}
messageBytes, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privateKey, decodedCiphertext, nil)
if err != nil {
return "", fmt.Errorf("decrypt ciphertext with private key err:%s", err)
}
return string(messageBytes), nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/eden-w2w/wechatpay-go.git
git@gitee.com:eden-w2w/wechatpay-go.git
eden-w2w
wechatpay-go
wechatpay-go
v0.2.12

搜索帮助