rsa.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return encrypted, nil
  18. }
  19. // DecryptWithRSA 使用 RSA 私钥解密数据
  20. func DecryptWithRSA(privateKey *rsa.PrivateKey, encrypted []byte) ([]byte, error) {
  21. hash, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, encrypted, nil)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return hash, nil
  26. }
  27. // 解析RSA公钥
  28. func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
  29. pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem")
  30. block, _ := pem.Decode(pemBlock)
  31. if block == nil {
  32. FileLog.Error("公钥解析失败")
  33. return nil, errors.New("公钥解析失败")
  34. }
  35. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  36. if err != nil {
  37. return nil, err
  38. }
  39. publicKey = key.(*rsa.PublicKey)
  40. return
  41. }