Files
servicebase/pkg/common/HyTools/RsaUtil.go
2025-11-18 17:48:20 +08:00

147 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package HyTools
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
)
// RSA加密
func RsaEncrypt(origData string, publicKey string) (string, error) {
block, _ := pem.Decode([]byte(publicKey)) //将密钥解析成公钥实例
if block == nil {
return "", errors.New("public key error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) //解析pem.Decode返回的Block指针实例
if err != nil {
return "", err
}
pub := pubInterface.(*rsa.PublicKey)
partLen := pub.N.BitLen()/8 - 11
chunks := ByteSplit([]byte(origData), partLen)
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
bytes, err := rsa.EncryptPKCS1v15(rand.Reader, pub, chunk)
if err != nil {
return "", err
}
buffer.Write(bytes)
}
return base64.StdEncoding.EncodeToString(buffer.Bytes()), nil
}
// RSA解密
func RsaDecrypt(ciphertext string, privateKey string) (string, error) {
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return "", errors.New("private key error!")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
partLen := priv.N.BitLen() / 8
raw, err := base64.StdEncoding.DecodeString(ciphertext)
chunks := ByteSplit([]byte(raw), partLen)
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, priv, chunk)
if err != nil {
return "", err
}
buffer.Write(decrypted)
}
return buffer.String(), err
}
// RSA SHA1加签
func RsaSHA1Sign(data string, privateKey string) (string, error) {
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return "", errors.New("Sign private key decode error")
}
prk8, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
h := sha1.New()
h.Write([]byte(data))
hashed := h.Sum(nil)
sign, err := rsa.SignPKCS1v15(rand.Reader, prk8, crypto.SHA1, hashed)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(sign), err
}
// RSA SHA1验签
func RsaSHA1Verify(data string, sign string, publicKey string) error {
h := sha1.New()
h.Write([]byte(data))
hashed := h.Sum(nil)
decodedSign, err := base64.StdEncoding.DecodeString(sign)
if err != nil {
return err
}
block, _ := pem.Decode([]byte(publicKey))
if block == nil {
return errors.New("Sign public key decode error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) //解析pem.Decode返回的Block指针实例
if err != nil {
return err
}
pub := pubInterface.(*rsa.PublicKey)
return rsa.VerifyPKCS1v15(pub, crypto.SHA1, hashed, decodedSign)
}