AWS4 Signature in GoLang



我最近又开始编程了,需要一些帮助,因为我已经用头撞键盘好几天了,但出来的代码似乎没有起到作用。。。我的项目范围很简单;向使用AWS身份验证的服务器发送API请求我已经实现了以下创建签名:

authString := "AWS4-HMAC-SHA256 Credential=**AWS Access**/"
authString += time.Now().Format("20060102" /*T150405Z"*/) + "/"
authString += "eu-west-1/"
authString += "execute-api/"
authString += "aws4_request,"
authString += "SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date"
awsSecret := "**tis a secret**"
/*
Pseudocode from documentation
kSecret = your secret access key
kDate = HMAC("AWS4" + kSecret, Date)
kRegion = HMAC(kDate, Region)
kService = HMAC(kRegion, Service)
kSigning = HMAC(kService, "aws4_request")
*/
hash := getHMAC([]byte("AWS4"+awsSecret), []byte(time.Now().Format("20060102")))
hash = getHMAC(hash, []byte("eu-west-1"))
hash = getHMAC(hash, []byte("execute-api"))
hash = getHMAC(hash, []byte("aws4_request"))
authString += ", Signature=" + hex.EncodeToString(hash)
return authString
}
func getHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}

签名字符串

AWS4-HMAC-SHA256 Credential=**AWS Access**/20200421/eu-west-1/execute-api/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date, Signature=7b0fe4780c1c5ba39d0dee1774135d81c0bcca85f5e83325299c245eba1b0e5e

响应

{"message":"The request signature we calculated does not match the signature you provided. Check your 
AWS Secret Access Key and signing method. Consult the service documentation for details.nnThe Canonical String for this request should have beenn'POSTn/prd/config/nncontent-type:application/jsonnhost:1294t77jvc.execute-api.eu-west-1.amazonaws.comnx-amz-content-sha256:nx-amz-date:2020-04-21T10:33:36+01:00nncontent-type;host;x-amz-content-sha256;x-amz-daten3cffc0f4da0132a4156d5c1a6506b4b163368ee9b131dce71e8316bd2220650b'nnThe String-to-Sign should have beenn'AWS4-HMAC-SHA256n20200421T093336Zn20200421/eu-west-1/execute-api/aws4_requestn3e40376452b02b8ba7f2826971e0438fd6891ccbf4c94e553dd91a2cc6f68560'n"}

请记住,响应是用一些伪造的数据,但这与它拥有真正的AWS Access和密钥几乎相同。随意批评你在那里看到的任何东西,因为我也在努力获得良好的实践

问候,

我设法基于您的脚本成功地解决了它。您缺少此模式的string_to_sign

stringToSign := algorithm + "n" + amzDate + "n" + credentialScope + "n" + hash(canonicalRequest)

并且应该包含在签名中。所以你必须喜欢

signatureWithStringToSign := GetHMAC(hash, []byte(stringToSign))  
authString += ", Signature=" + hex.EncodeToString(signatureWithStringToSign)

最新更新