rsa_utils.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package auth
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. logger "eta/eta_mini_ht_api/common/component/log"
  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 string) ([]byte, error) {
  24. encKey, _ := base64.StdEncoding.DecodeString(encrypted)
  25. hash, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encKey)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return hash, nil
  30. }
  31. // ParsePrivateKeyFromPEM 解析RSA公钥
  32. func ParsePrivateKeyFromPEM() (privateKey *rsa.PrivateKey, err error) {
  33. pemBlock, err := os.ReadFile("./conf/rsa_private_key.pem")
  34. block, _ := pem.Decode(pemBlock)
  35. if block == nil {
  36. logger.Error("私钥解析失败")
  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. func ParsePrivateKey(configPath string) (privateKey *rsa.PrivateKey, err error) {
  46. pemBlock, err := os.ReadFile(configPath)
  47. block, _ := pem.Decode(pemBlock)
  48. if block == nil {
  49. logger.Error("私钥解析失败")
  50. return nil, errors.New("私钥解析失败")
  51. }
  52. privateInfo, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  53. if err != nil {
  54. return nil, err
  55. }
  56. privateKey = privateInfo.(*rsa.PrivateKey)
  57. return
  58. }
  59. // ParsePublicKeyFromPEM 解析RSA公钥
  60. func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
  61. pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem")
  62. block, _ := pem.Decode(pemBlock)
  63. if block == nil {
  64. logger.Error("公钥解析失败")
  65. return nil, errors.New("公钥解析失败")
  66. }
  67. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  68. if err != nil {
  69. return nil, err
  70. }
  71. publicKey = key.(*rsa.PublicKey)
  72. return
  73. }