rsa.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/pem"
  8. "errors"
  9. "os"
  10. )
  11. // EncryptWithRSA 使用 RSA 公钥加密数据
  12. func EncryptWithRSA(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
  13. hash := sha256.Sum256(data)
  14. encrypted, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, hash[:], nil)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return encrypted, nil
  19. }
  20. // DecryptWithRSA 使用 RSA 私钥解密数据
  21. func DecryptWithRSA(privateKey *rsa.PrivateKey, encrypted []byte) ([]byte, error) {
  22. hash, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
  23. if err != nil {
  24. return nil, err
  25. }
  26. return hash, nil
  27. }
  28. // 解析RSA公钥
  29. func ParsePrivateKeyFromPEM(path string) (privateKey *rsa.PrivateKey, err error) {
  30. pemBlock, err := os.ReadFile(path + "rsa_private_key.pem")
  31. block, _ := pem.Decode(pemBlock)
  32. if block == nil {
  33. return nil, errors.New("私钥解析失败")
  34. }
  35. privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  36. if err != nil {
  37. return nil, err
  38. }
  39. return
  40. }