API 认证参数
所有接口都需要以下通用认证参数,请参考以下示例。
- Name
AccessKeyId- Type
- string
- Description
用户的访问密钥 ID
- Name
SignatureNonce- Type
- string
- Description
签名随机数
- Name
Timestamp- Type
- string
- Description
请求时间戳(秒),有效期 30 秒
- Name
Signature- Type
- string
- Description
使用 HmacSHA1 + Base64 生成的签名
参考示例
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"math/rand"
"strconv"
"time"
)
// GenerateSignature 生成 API 签名
func GenerateSignature(accessKeyId, accessSecret string, signatureNonce *string, timestamp *int64) string {
nonce := ""
if signatureNonce == nil {
b := make([]byte, 4)
rand.Read(b)
nonce = hex.EncodeToString(b)
} else {
nonce = *signatureNonce
}
ts := ""
if timestamp == nil {
ts = strconv.FormatInt(time.Now().Unix(), 10)
} else {
ts = strconv.FormatInt(*timestamp, 10)
}
str := fmt.Sprintf("AccessKeyId=%s&SignatureNonce=%s&Timestamp=%s",
accessKeyId, nonce, ts)
h := hmac.New(sha1.New, []byte(accessSecret))
h.Write([]byte(str))
hexSignature := hex.EncodeToString(h.Sum(nil))
return base64.StdEncoding.EncodeToString([]byte(hexSignature))
}
func main() {
accessKeyId := "975988f45090561684b7d8f4e45b85c2"
accessSecret := "957f23f2d6435e37d4ac21f3e9a67d45"
signatureNonce := "2"
timestamp := int64(1612149637)
newSignature := GenerateSignature(
accessKeyId,
accessSecret,
&signatureNonce,
×tamp,
)
oldSignature := "M2Y0ODNlYTUwNDFiMTg5MjRmMGQxNmY1YTMyMzc1NTc5NTUzNDAzYw=="
if newSignature == oldSignature {
fmt.Println("签名验证成功")
} else {
fmt.Println("签名验证失败")
}
fmt.Println("新生成的签名:", newSignature)
}