AWS请求身份验证:编码标头

huangapple go评论116阅读模式
英文:

AWS Request Authentication: Encode Header

问题

package main

import "fmt"
import "crypto/hmac"
import "crypto/sha256"
import "time"
import "encoding/base64"

func main() {
AWSAccessKeyId := "MHAPUBLICKEY"
AWSSecretKeyId := "MHAPRIVATEKEY"
sha256 := sha256.New
time := time.Now().UTC().Format(time.ANSIC)
hash := hmac.New(sha256, []byte(AWSSecretKeyId))
hash.Write([]byte(time))
sha := base64.URLEncoding.EncodeToString(hash.Sum(nil))

fmt.Println("Date", time)
fmt.Println("Content-Type","text/xml; charset=UTF-8")
fmt.Println("AWS3-HTTPS AWSAccessKeyId=" + AWSAccessKeyId + ",Algorithm=HmacSHA256,Signature=" + sha)
}

英文:

My implementation of AWS Request Authentication in Google Go lang

  1. package main
  2. import "fmt"
  3. import "crypto/hmac"
  4. import "crypto/sha256"
  5. import "time"
  6. import "encoding/base64"
  7. func main() {
  8. AWSAccessKeyId := "MHAPUBLICKEY"
  9. AWSSecretKeyId := "MHAPRIVATEKEY"
  10. sha256 := sha256.New
  11. time := time.Now().UTC().Format(time.ANSIC)
  12. hash := hmac.New(sha256, []byte(AWSSecretKeyId))
  13. hash.Write([]byte(time))
  14. sha := base64.URLEncoding.EncodeToString(hash.Sum(nil))
  15. fmt.Println("Date", time)
  16. fmt.Println("Content-Type","text/xml; charset=UTF-8")
  17. fmt.Println("AWS3-HTTPS AWSAccessKeyId=" + AWSAccessKeyId + ",Algorithm=HmacSHA256,Signature=" + sha)
  18. }

I get valid output from Amazon but only when the 'sha' hash does not contain any _ or -

Working
> 'WFKzWNQlZEyTC9JFGFyqdf8AYj54aBj5btxPIaGTDbM='

Not Working HTTP/1.1 403 Forbidden SignatureDoesNotMatch
> 'h-FIs7of_CJ7LusAoQPzSWVt9hlXF_5gCQgedn_85lk='

How do I encode the AWS3-HTTPS header so it works in either circumstance? Just incase it's relevant, I am currently copy and pasting the output into cURL. I plan on implementing the request in Google Go once I have it working reliably.

答案1

得分: 4

我发现我需要从URLEncoding更改为StdEncoding

  1. sha = base64.StdEncoding.EncodeToString(hash.Sum(nil))

  1. sha = base64.StdEncoding.EncodeToString(hash.Sum(nil))
英文:

I turned out I needed to change from URLEncoding to StdEncoding

  1. sha = base64.URLEncoding.EncodeToString(hash.Sum(nil))

to

  1. sha = base64.StdEncoding.EncodeToString(hash.Sum(nil))

huangapple
  • 本文由 发表于 2013年4月17日 05:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/16047506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定