1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- package utils
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "encoding/pem"
- "errors"
- "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)
- if block == nil {
- return nil, errors.New("私钥解析失败")
- }
- privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- return
- }
|