rsa_utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // ParsePublicKeyFromPEM 解析RSA公钥
  46. func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
  47. pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem")
  48. block, _ := pem.Decode(pemBlock)
  49. if block == nil {
  50. logger.Error("公钥解析失败")
  51. return nil, errors.New("公钥解析失败")
  52. }
  53. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  54. if err != nil {
  55. return nil, err
  56. }
  57. publicKey = key.(*rsa.PublicKey)
  58. return
  59. }