ref: DRY hmac method (#1)

This commit is contained in:
Joe Paul
2018-12-07 11:57:08 +05:30
committed by Rohan Verma
parent 157aa88554
commit 41b1c70183
2 changed files with 15 additions and 22 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ var NowTime = func() time.Time {
return time.Now() return time.Now()
} }
var lf = []byte{'\n'} var newLine = []byte{'\n'}
// CreateUploadPolicies creates amazon s3 sigv4 compatible // CreateUploadPolicies creates amazon s3 sigv4 compatible
// policy and signing keys with the signature returns the upload policy. // policy and signing keys with the signature returns the upload policy.
+14 -21
View File
@@ -7,7 +7,6 @@ package simples3
import ( import (
"bytes" "bytes"
"crypto/hmac"
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"io" "io"
@@ -21,10 +20,10 @@ import (
) )
func (s3 *S3) signKeys(t time.Time) []byte { func (s3 *S3) signKeys(t time.Time) []byte {
h := ghmac([]byte("AWS4"+s3.SecretKey), []byte(t.Format(shortTimeFormat))) h := makeHMac([]byte("AWS4"+s3.SecretKey), []byte(t.Format(shortTimeFormat)))
h = ghmac(h, []byte(s3.Region)) h = makeHMac(h, []byte(s3.Region))
h = ghmac(h, []byte(serviceName)) h = makeHMac(h, []byte(serviceName))
h = ghmac(h, []byte("aws4_request")) h = makeHMac(h, []byte("aws4_request"))
return h return h
} }
@@ -32,27 +31,27 @@ func (s3 *S3) writeRequest(w io.Writer, r *http.Request) {
r.Header.Set("host", r.Host) r.Header.Set("host", r.Host)
w.Write([]byte(r.Method)) w.Write([]byte(r.Method))
w.Write(lf) w.Write(newLine)
writeURI(w, r) writeURI(w, r)
w.Write(lf) w.Write(newLine)
writeQuery(w, r) writeQuery(w, r)
w.Write(lf) w.Write(newLine)
writeHeader(w, r) writeHeader(w, r)
w.Write(lf) w.Write(newLine)
w.Write(lf) w.Write(newLine)
writeHeaderList(w, r) writeHeaderList(w, r)
w.Write(lf) w.Write(newLine)
writeBody(w, r) writeBody(w, r)
} }
func (s3 *S3) writeStringToSign(w io.Writer, t time.Time, r *http.Request) { func (s3 *S3) writeStringToSign(w io.Writer, t time.Time, r *http.Request) {
w.Write([]byte("AWS4-HMAC-SHA256")) w.Write([]byte("AWS4-HMAC-SHA256"))
w.Write(lf) w.Write(newLine)
w.Write([]byte(t.Format(amzDateISO8601TimeFormat))) w.Write([]byte(t.Format(amzDateISO8601TimeFormat)))
w.Write(lf) w.Write(newLine)
w.Write([]byte(s3.creds(t))) w.Write([]byte(s3.creds(t)))
w.Write(lf) w.Write(newLine)
h := sha256.New() h := sha256.New()
s3.writeRequest(h, r) s3.writeRequest(h, r)
@@ -108,7 +107,7 @@ func writeHeader(w io.Writer, r *http.Request) {
sort.Strings(a) sort.Strings(a)
for i, s := range a { for i, s := range a {
if i > 0 { if i > 0 {
w.Write(lf) w.Write(newLine)
} }
io.WriteString(w, s) io.WriteString(w, s)
} }
@@ -148,9 +147,3 @@ func writeBody(w io.Writer, r *http.Request) {
h.Write(b) h.Write(b)
fmt.Fprintf(w, "%x", h.Sum(nil)) fmt.Fprintf(w, "%x", h.Sum(nil))
} }
func ghmac(key, data []byte) []byte {
h := hmac.New(sha256.New, key)
h.Write(data)
return h.Sum(nil)
}