xy_sh-20260724115439/xy_sh/internal/middleware/middleware.go

63 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
}
}