17 const requiredSigHeaders = "(request-target) host date digest"
19 // Sign signs the given HTTP request with the matching private key of the
20 // public key available at pubkeyURL.
21 func Sign(req *http.Request, key *rsa.PrivateKey, pubkeyURL string) error {
22 date := time.Now().UTC().Format(http.TimeFormat)
23 req.Header.Set("Date", date)
25 fmt.Fprintln(hash, "(request-target):", strings.ToLower(req.Method), req.URL.Path)
26 fmt.Fprintln(hash, "host:", req.URL.Hostname())
27 fmt.Fprintln(hash, "date:", date)
29 buf := &bytes.Buffer{}
30 io.Copy(buf, req.Body)
32 req.Body = io.NopCloser(buf)
33 digest := sha256.Sum256(buf.Bytes())
34 d := "SHA-256=" + base64.StdEncoding.EncodeToString(digest[:])
35 fmt.Fprintf(hash, "digest: %s", d)
36 req.Header.Set("Digest", d)
38 sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hash.Sum(nil))
42 bsig := base64.StdEncoding.EncodeToString(sig)
44 sigKeys := "(request-target) host date digest"
45 val := fmt.Sprintf("keyId=%q,algorithm=%q,headers=%q,signature=%q", pubkeyURL, "rsa-sha256", sigKeys, bsig)
46 req.Header.Set("Signature", val)
50 type signature struct {
57 func parseSignatureHeader(line string) (signature, error) {
59 for _, v := range strings.Split(line, ",") {
60 name, val, ok := strings.Cut(v, "=")
62 return sig, fmt.Errorf("bad field: %s from %s", v, line)
64 val = strings.Trim(val, `"`)
75 return signature{}, fmt.Errorf("bad field name %s", name)
80 return sig, fmt.Errorf("missing signature field keyId")
81 } else if sig.algorithm == "" {
82 return sig, fmt.Errorf("missing signature field algorithm")
83 } else if sig.headers == "" {
84 return sig, fmt.Errorf("missing signature field headers")
85 } else if sig.signature == "" {
86 return sig, fmt.Errorf("missing signature field signature")