Blob


1 package apub
3 import (
4 "bytes"
5 "crypto"
6 "crypto/rand"
7 "crypto/rsa"
8 "crypto/sha256"
9 "encoding/base64"
10 "fmt"
11 "io"
12 "net/http"
13 "strings"
14 "time"
15 )
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)
24 hash := sha256.New()
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)
31 req.Body.Close()
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))
39 if err != nil {
40 return err
41 }
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)
47 return nil
48 }
50 type signature struct {
51 keyID string
52 algorithm string
53 headers string
54 signature string
55 }
57 func parseSignatureHeader(line string) (signature, error) {
58 var sig signature
59 for _, v := range strings.Split(line, ",") {
60 name, val, ok := strings.Cut(v, "=")
61 if !ok {
62 return sig, fmt.Errorf("bad field: %s from %s", v, line)
63 }
64 val = strings.Trim(val, `"`)
65 switch name {
66 case "keyId":
67 sig.keyID = val
68 case "algorithm":
69 sig.algorithm = val
70 case "headers":
71 sig.headers = val
72 case "signature":
73 sig.signature = val
74 default:
75 return signature{}, fmt.Errorf("bad field name %s", name)
76 }
77 }
79 if sig.keyID == "" {
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")
87 }
88 return sig, nil
89 }