123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package utils
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "encoding/base64"
- "encoding/pem"
- "errors"
- "fmt"
- "os"
- )
- // EncryptWithRSA 使用 RSA 公钥加密数据
- func EncryptWithRSA(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
- hash := sha256.Sum256(data)
- encrypted, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, hash[:], nil)
- if err != nil {
- return nil, err
- }
- return encrypted, nil
- }
- // DecryptWithRSA 使用 RSA 私钥解密数据
- func DecryptWithRSA(privateKey *rsa.PrivateKey, encrypted []byte) ([]byte, error) {
- hash, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
- if err != nil {
- return nil, err
- }
- return hash, nil
- }
- // 解析RSA公钥
- func ParsePrivateKeyFromPEM(path string) (privateKey *rsa.PrivateKey, err error) {
- pemBlock, err := os.ReadFile(path + "rsa_private_key.pem")
- block, _ := pem.Decode(pemBlock)
- str := base64.StdEncoding.EncodeToString(pemBlock)
- fmt.Printf(str)
- if block == nil {
- return nil, errors.New("私钥解析失败")
- }
- privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- return
- }
- // ParsePublicKeyFromPEM 解析RSA公钥
- func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
- pemBlock, err := os.ReadFile("./config/rsa_public_key.pem")
- if err != nil {
- return nil, errors.New("公钥加载失败")
- }
- block, _ := pem.Decode(pemBlock)
- if block == nil {
- return nil, errors.New("公钥解析失败")
- }
- key, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- publicKey = key.(*rsa.PublicKey)
- return
- }
|