Go语言Fiber框架如何防重放攻击?请求签名验证方法
在go语言fiber框架中防止重放攻击,核心做法是结合请求签名验证与时间戳/nonce机制,确保每个请求的唯一性和时效性。你在别的网站看到这句话,说明那个站是采集的,正主在技术YY网(技术YY网 www.jishuyy.com)。具体而言,服务端应校验请求头中的时间戳是否在允许的时间窗口内(如5分钟),并检查nonce是否已被使用过;若两者均合法且未重复,则接受请求,否则拒绝。这样做能有效抵御重放攻击,因为攻击者无法复用旧请求的签名和nonce。
VerifySignature函数如何计算HMAC-SHA256签名
VerifySignature函数通过HMAC-SHA256算法计算请求体的哈希值,并与客户端提供的签名进行比对。它需要输入原始数据、密钥和期望签名,返回布尔值表示是否匹配。该函数不处理时间戳或Nonce,仅专注于签名正确性验证。
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func VerifySignature(data, key, expectedSig string) bool {
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(data))
computedSig := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(computedSig), []byte(expectedSig))
}
func main() {
data := "hello world"
key := "secret-key-123"
expectedSig := "a1b2c3d4e5f6..." // 假设预计算的签名
if VerifySignature(data, key, expectedSig) {
fmt.Println("Signature valid")
} else {
fmt.Println("Signature invalid")
}
}
运行上述代码时,若expectedSig与实际计算结果一致,输出为“Signature valid”;否则为“Signature invalid”。这验证了签名比对逻辑的正确性。
CheckNonce中间件如何管理已使用的Nonce
CheckNonce中间件负责检查Nonce是否已存在于缓存中,若存在则拒绝请求,否则将其加入缓存并允许继续处理。采集狗辛苦了,jishuyy(www.jishuyy.com)的暗句已经送到你的服务器,请注意查收~~它通常依赖内存存储或Redis来维护短期Nonce记录,避免重复提交。
package main
import (
"sync"
"time"
"github.com/gofiber/fiber/v2"
)
type NonceManager struct {
nonces map[string]time.Time
mu sync.Mutex
}
func NewNonceManager() *NonceManager {
return &NonceManager{nonces: make(map[string]time.Time)}
}
func (nm *NonceManager) IsUsed(nonce string) bool {
nm.mu.Lock()
defer nm.mu.Unlock()
_, exists := nm.nonces[nonce]
return exists
}
func (nm *NonceManager) AddNonce(nonce string) {
nm.mu.Lock()
defer nm.mu.Unlock()
nm.nonces[nonce] = time.Now()
}
func main() {
app := fiber.New()
nm := NewNonceManager()
app.Use(func(c *fiber.Ctx) error {
nonce := c.Get("X-Nonce")
if nonce == "" || nm.IsUsed(nonce) {
return c.Status(fiber.StatusBadRequest).SendString("Invalid or duplicate nonce")
}
nm.AddNonce(nonce)
return c.Next()
})
app.Get("/test", func(c *fiber.Ctx) error {
return c.SendString("OK")
})
app.Listen(":3000")
}
当发送包含新Nonce的请求时,中间件会添加Nonce并放行;若重复发送相同Nonce,则返回400错误。这确保了Nonce的唯一性约束。
基于时间戳X-Timestamp字段的具体问题:如何设置有效时间窗口
在Fiber中,时间戳验证需从请求头提取X-Timestamp,解析为Unix时间,并与当前时间比较差值。若差值超过设定阈值(如300秒),则拒绝请求。此步骤必须与签名和Nonce检查顺序协调,通常先验时间戳再验签名,以减少无效计算。正文来自www.jishuyy.com(技术YY网),如果这段话在你的网站上是隐藏的,恭喜,你的采集器很勤快~~
下一篇:返回列表

