From 917dbeba5246c2945124f8cb3ea331192c6626be Mon Sep 17 00:00:00 2001 From: renzhiyuan <465386466@qq.com> Date: Fri, 24 Jul 2026 11:54:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=96=87=E4=BB=B6:=20xy=5Fsh?= =?UTF-8?q?/internal/middleware/middleware.go?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xy_sh/internal/middleware/middleware.go | 63 +++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 xy_sh/internal/middleware/middleware.go diff --git a/xy_sh/internal/middleware/middleware.go b/xy_sh/internal/middleware/middleware.go new file mode 100644 index 0000000..c89b084 --- /dev/null +++ b/xy_sh/internal/middleware/middleware.go @@ -0,0 +1,63 @@ +package middleware + +import ( + "encoding/json" + "strings" + + "github.com/gofiber/fiber/v2" + "xy_sh/internal/config" + "xy_sh/pkg/crypto" +) + +// VerifySign 验证签名中间件 +func VerifySign(cfg *config.Config) fiber.Handler { + return func(c *fiber.Ctx) error { + timestamp := c.Get("timestamp") + sign := c.Get("sign") + + if timestamp == "" || sign == "" { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "code": -1, + "msg": "缺少timestamp或sign请求头", + }) + } + + body := c.Body() + if len(body) == 0 { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "code": -1, + "msg": "请求体不能为空", + }) + } + + var req struct { + EncryptedData string `json:"encryptedData"` + } + if err := json.Unmarshal(body, &req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "code": -1, + "msg": "请求体格式错误", + }) + } + + // 验证签名:SM3(salt + timestamp + encryptedData) + expectedSign := crypto.SM3WithSalt(timestamp+req.EncryptedData, cfg.SM3Salt) + if !strings.EqualFold(expectedSign, sign) { + return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{ + "code": -1, + "msg": "签名验证失败", + }) + } + + decrypted, err := crypto.SM4ECBDecrypt(req.EncryptedData, cfg.SM4Key) + if err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "code": -1, + "msg": "解密失败: " + err.Error(), + }) + } + + c.Locals("decryptedBody", decrypted) + return c.Next() + } +} \ No newline at end of file