diff --git a/common.go b/common.go index 432216a..aa58c85 100644 --- a/common.go +++ b/common.go @@ -1,6 +1,7 @@ package awsauth import ( + "bytes" "crypto/hmac" "crypto/md5" "crypto/sha1" @@ -73,9 +74,9 @@ func hmacSHA1(key []byte, content string) []byte { return mac.Sum(nil) } -func hashSHA256(content string) string { +func hashSHA256(content []byte) string { h := sha256.New() - h.Write([]byte(content)) + h.Write(content) return fmt.Sprintf("%x", h.Sum(nil)) } @@ -85,13 +86,12 @@ func hashMD5(content []byte) string { return base64.StdEncoding.EncodeToString(h.Sum(nil)) } -func readAndReplaceBody(req *http.Request) string { +func readAndReplaceBody(req *http.Request) []byte { if req.Body == nil { - return "" + return []byte{} } - rawPayload, _ := ioutil.ReadAll(req.Body) - payload := string(rawPayload) - req.Body = ioutil.NopCloser(strings.NewReader(payload)) + payload, _ := ioutil.ReadAll(req.Body) + req.Body = ioutil.NopCloser(bytes.NewReader(payload)) return payload } diff --git a/common_test.go b/common_test.go index 87e9fb9..ac8482c 100644 --- a/common_test.go +++ b/common_test.go @@ -36,7 +36,7 @@ func TestCommonFunctions(t *testing.T) { }) Convey("SHA-256 hashes should be properly hex-encoded (base 16)", t, func() { - input := "This is... Sparta!!" + input := []byte("This is... Sparta!!") actual := hashSHA256(input) So(actual, ShouldEqual, "5c81a4ef1172e89b1a9d575f4cd82f4ed20ea9137e61aa7f1ab936291d24e79a") diff --git a/s3.go b/s3.go index 34b7a20..363e869 100644 --- a/s3.go +++ b/s3.go @@ -14,10 +14,12 @@ func signatureS3(stringToSign string) string { } func stringToSignS3(req *http.Request) string { - str := req.Method + "\n" - // TODO: Content-MD5 here... + body := readAndReplaceBody(req) + if len(body) > 0 { + str += hashMD5(body) + } str += "\n" str += req.Header.Get("Content-Type") + "\n" diff --git a/sign4.go b/sign4.go index 5aa4463..9d8361b 100644 --- a/sign4.go +++ b/sign4.go @@ -17,7 +17,7 @@ func hashedCanonicalRequestV4(req *http.Request, meta *metadata) string { meta.signedHeaders = "content-type;host;x-amz-date" canonicalRequest := concat("\n", req.Method, req.URL.Path, req.URL.RawQuery, headersToSign, meta.signedHeaders, hashedPayload) - return hashSHA256(canonicalRequest) + return hashSHA256([]byte(canonicalRequest)) } func stringToSignV4(req *http.Request, hashedCanonReq string, meta *metadata) string { diff --git a/sign4_test.go b/sign4_test.go index 394f35a..2504c6a 100644 --- a/sign4_test.go +++ b/sign4_test.go @@ -123,13 +123,13 @@ func TestSignature4Helpers(t *testing.T) { req := test_plainRequestV4(false) Convey("Its body should be read and replaced without differences", func() { - expected := requestValuesV4.Encode() + expected := []byte(requestValuesV4.Encode()) actual1 := readAndReplaceBody(req) - So(actual1, ShouldEqual, expected) + So(actual1, ShouldResemble, expected) actual2 := readAndReplaceBody(req) - So(actual2, ShouldEqual, expected) + So(actual2, ShouldResemble, expected) }) }) }