signature_interceptor.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package rpc
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/rsa"
  6. "crypto/sha256"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "encoding/pem"
  10. "eta/eta_bridge/global"
  11. "google.golang.org/grpc"
  12. "os"
  13. )
  14. type encryptedRequest struct {
  15. Message interface{} `json:"ciphertext"`
  16. Nonce string `json:"nonce"` // 添加随机字符串
  17. Timestamp int64 `json:"timestamp"` // 添加时间戳
  18. }
  19. // 签名验证拦截器
  20. func SignatureInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  21. return handler(ctx, req)
  22. }
  23. // 验证签名
  24. func verifySignature(message []byte, signature string, publicKey *rsa.PublicKey) bool {
  25. hash := sha256.Sum256(message)
  26. signatureBytes, err := base64.StdEncoding.DecodeString(signature)
  27. if err != nil {
  28. return false
  29. }
  30. err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hash[:], signatureBytes)
  31. return err == nil
  32. }
  33. func parsePublicKeyFromPEM() (pubKey *rsa.PublicKey, err error) {
  34. pemBlock, err := os.ReadFile("./config/rsa_public_key.pem")
  35. block, _ := pem.Decode(pemBlock)
  36. if block == nil {
  37. global.LOG.Error("公钥解析失败")
  38. }
  39. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  40. pubKey, ok := pubInterface.(*rsa.PublicKey)
  41. if !ok {
  42. global.LOG.Error("公钥解析失败")
  43. }
  44. if err != nil {
  45. return nil, err
  46. }
  47. return
  48. }