rsa.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "os"
  12. )
  13. // EncryptWithRSA 使用 RSA 公钥加密数据
  14. func EncryptWithRSA(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
  15. hash := sha256.Sum256(data)
  16. encrypted, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, hash[:], nil)
  17. if err != nil {
  18. return nil, err
  19. }
  20. return encrypted, nil
  21. }
  22. // DecryptWithRSA 使用 RSA 私钥解密数据
  23. func DecryptWithRSA(privateKey *rsa.PrivateKey, encrypted []byte) ([]byte, error) {
  24. hash, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
  25. if err != nil {
  26. return nil, err
  27. }
  28. return hash, nil
  29. }
  30. // 解析RSA公钥
  31. func ParsePrivateKeyFromPEM(path string) (privateKey *rsa.PrivateKey, err error) {
  32. pemBlock, err := os.ReadFile(path + "rsa_private_key.pem")
  33. block, _ := pem.Decode(pemBlock)
  34. str := base64.StdEncoding.EncodeToString(pemBlock)
  35. fmt.Printf(str)
  36. if block == nil {
  37. return nil, errors.New("私钥解析失败")
  38. }
  39. privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return
  44. }
  45. // ParsePublicKeyFromPEM 解析RSA公钥
  46. func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
  47. pemBlock, err := os.ReadFile("./config/rsa_public_key.pem")
  48. if err != nil {
  49. return nil, errors.New("公钥加载失败")
  50. }
  51. block, _ := pem.Decode(pemBlock)
  52. if block == nil {
  53. return nil, errors.New("公钥解析失败")
  54. }
  55. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  56. if err != nil {
  57. return nil, err
  58. }
  59. publicKey = key.(*rsa.PublicKey)
  60. return
  61. }