欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > Golang做API开发离不开签名验证,如何设计 ?

Golang做API开发离不开签名验证,如何设计 ?

2025/8/27 23:06:53 来源:https://blog.csdn.net/leyang0910/article/details/141028542  浏览:    关键词:Golang做API开发离不开签名验证,如何设计 ?

在API开发中,签名验证是一种常见的安全措施,用于确保请求的完整性和来源的可靠性。以下是设计一个签名验证机制的步骤和示例代码。

设计思路
  1. 密钥管理:为每个客户端分配一个唯一的API密钥和API密钥。
  2. 签名生成:客户端在请求API时,使用预定义的算法生成签名,并将签名和其他必要参数(如时间戳、随机数等)一起发送到服务器。
  3. 签名验证:服务器接收到请求后,根据相同的算法重新生成签名,并与请求中的签名进行对比,如果匹配,则验证通过。
签名生成与验证步骤
  1. 客户端:
  • 生成时间戳和随机数。
  • 将API密钥、时间戳、随机数、请求参数等按照预定义的顺序拼接成字符串。
  • 使用API密钥对字符串进行哈希运算(如HMAC-SHA256)生成签名。
  • 将签名、时间戳、随机数等信息作为请求参数发送到服务器。
  1. 服务器:
  • 从请求中提取签名、时间戳、随机数等信息。
  • 验证时间戳是否在合理范围内(防止重放攻击)。
  • 根据相同的算法重新生成签名。
  • 对比服务器生成的签名和请求中的签名,如果匹配,则验证通过。
示例代码

以下是一个简单的Go语言实现,用于演示API签名验证。

客户端代码
package mainimport ("crypto/hmac""crypto/sha256""encoding/hex""fmt""net/http""net/url""strconv""time"
)func generateSignature(apiSecret, apiKey, timestamp, nonce string, params url.Values) string {message := apiKey + timestamp + nonce + params.Encode()mac := hmac.New(sha256.New, []byte(apiSecret))mac.Write([]byte(message))signature := hex.EncodeToString(mac.Sum(nil))return signature
}func main() {apiKey := "your_api_key"apiSecret := "your_api_secret"timestamp := strconv.FormatInt(time.Now().Unix(), 10)nonce := "random_nonce"params := url.Values{}params.Set("param1", "value1")params.Set("param2", "value2")signature := generateSignature(apiSecret, apiKey, timestamp, nonce, params)req, err := http.NewRequest("GET", "http://example.com/api", nil)if err != nil {fmt.Println("Error creating request:", err)return}query := req.URL.Query()query.Add("apiKey", apiKey)query.Add("timestamp", timestamp)query.Add("nonce", nonce)query.Add("signature", signature)req.URL.RawQuery = query.Encode()client := &http.Client{}resp, err := client.Do(req)if err != nil {fmt.Println("Error making request:", err)return}defer resp.Body.Close()fmt.Println("Response status:", resp.Status)
}
服务器端代码
package mainimport ("crypto/hmac""crypto/sha256""encoding/hex""fmt""net/http""net/url""strconv""time"
)const (apiKey    = "your_api_key"apiSecret = "your_api_secret"
)func generateSignature(apiSecret, apiKey, timestamp, nonce string, params url.Values) string {message := apiKey + timestamp + nonce + params.Encode()mac := hmac.New(sha256.New, []byte(apiSecret))mac.Write([]byte(message))return hex.EncodeToString(mac.Sum(nil))
}func validateSignature(r *http.Request) bool {apiKey := r.URL.Query().Get("apiKey")timestamp := r.URL.Query().Get("timestamp")nonce := r.URL.Query().Get("nonce")signature := r.URL.Query().Get("signature")if apiKey != apiKey {return false}timeInt, err := strconv.ParseInt(timestamp, 10, 64)if err != nil {return false}if time.Now().Unix()-timeInt > 300 {return false}params := r.URL.Query()params.Del("signature")expectedSignature := generateSignature(apiSecret, apiKey, timestamp, nonce, params)return hmac.Equal([]byte(signature), []byte(expectedSignature))
}func handler(w http.ResponseWriter, r *http.Request) {if !validateSignature(r) {http.Error(w, "Invalid signature", http.StatusUnauthorized)return}fmt.Fprintf(w, "Request is authenticated")
}func main() {http.HandleFunc("/api", handler)http.ListenAndServe(":8080", nil)
}
代码说明
  • 客户端:
  • generateSignature函数生成签名。
  • 使用当前时间戳和随机数生成签名,并将签名和其他必要参数添加到请求中。
  • 服务器端:
  • generateSignature函数用于重新生成签名。
  • validateSignature函数验证请求中的签名,包括检查时间戳是否在合理范围内,防止重放攻击。
  • handler函数处理请求并验证签名,如果验证通过,则返回成功响应。

通过这种方式,API请求可以通过签名验证机制确保请求的完整性和来源的可靠性,有效防止重放攻击和篡改。 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词