添加文件: xy_sh/internal/middleware/middleware.go
This commit is contained in:
parent
c4ab780caf
commit
917dbeba52
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue