this repo has no description
1package knotserver 2 3import ( 4 "crypto/hmac" 5 "crypto/sha256" 6 "encoding/hex" 7 "net/http" 8) 9 10func (h *Handle) VerifySignature(next http.Handler) http.Handler { 11 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 12 signature := r.Header.Get("X-Signature") 13 if signature == "" || !h.verifyHMAC(signature, r) { 14 writeError(w, "signature verification failed", http.StatusForbidden) 15 return 16 } 17 next.ServeHTTP(w, r) 18 }) 19} 20 21func (h *Handle) verifyHMAC(signature string, r *http.Request) bool { 22 secret := h.c.Secret 23 message := r.Method + r.URL.Path + r.URL.RawQuery 24 25 mac := hmac.New(sha256.New, []byte(secret)) 26 mac.Write([]byte(message)) 27 expectedMAC := mac.Sum(nil) 28 29 signatureBytes, err := hex.DecodeString(signature) 30 if err != nil { 31 return false 32 } 33 34 return hmac.Equal(signatureBytes, expectedMAC) 35}