func NewDigestAuthenticator(realm string, secrets SecretProvider) *DigestAuth {
	da := &DigestAuth{
		Opaque:               RandomKey(),
		Realm:                realm,
		Secrets:              secrets,
		PlainTextSecrets:     false,
		ClientCacheSize:      DefaultClientCacheSize,
		ClientCacheTolerance: DefaultClientCacheTolerance,
		clients:              map[string]*digestClient{}}
	return da
}
NewDigestAuthenticator generates a new DigestAuth object
package auth
import (
	"context"
	"crypto/subtle"
	"fmt"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)
type digestClient struct {
	nc       uint64
	lastSeen int64
}
type DigestAuth struct {
	Realm            string
	Opaque           string
	Secrets          SecretProvider
	PlainTextSecrets bool
	IgnoreNonceCount bool
	Headers *Headers
	ClientCacheSize      int
	ClientCacheTolerance int
	clients map[string]*digestClient
	mutex   sync.RWMutex
}
var _ = (AuthenticatorInterface)((*DigestAuth)(nil))
type digestCacheEntry struct {
	nonce    string
	lastSeen int64
}
type digestCache []digestCacheEntry
func (c digestCache) Less(i, j int) bool {
	return c[i].lastSeen < c[j].lastSeen
}
func (c digestCache) Len() int {
	return len(c)
}
func (c digestCache) Swap(i, j int) {
	c[i], c[j] = c[j], c[i]
}
func (da *DigestAuth) Purge(count int) {
	da.mutex.Lock()
	da.purgeLocked(count)
	da.mutex.Unlock()
}
func (da *DigestAuth) purgeLocked(count int) {
	entries := make([]digestCacheEntry, 0, len(da.clients))
	for nonce, client := range da.clients {
		entries = append(entries, digestCacheEntry{nonce, client.lastSeen})
	}
	cache := digestCache(entries)
	sort.Sort(cache)
	for _, client := range cache[:count] {
		delete(da.clients, client.nonce)
	}
}
func (da *DigestAuth) RequireAuth(w http.ResponseWriter, r *http.Request) {
	da.mutex.RLock()
	clientsLen := len(da.clients)
	da.mutex.RUnlock()
	if clientsLen > da.ClientCacheSize+da.ClientCacheTolerance {
		da.Purge(da.ClientCacheTolerance * 2)
	}
	nonce := RandomKey()
	da.mutex.Lock()
	da.clients[nonce] = &digestClient{nc: 0, lastSeen: time.Now().UnixNano()}
	da.mutex.Unlock()
	da.mutex.RLock()
	w.Header().Set(contentType, da.Headers.V().UnauthContentType)
	w.Header().Set(da.Headers.V().Authenticate,
		fmt.Sprintf(`Digest realm="%s", nonce="%s", opaque="%s", algorithm=MD5, qop="auth"`,
			da.Realm, nonce, da.Opaque))
	w.WriteHeader(da.Headers.V().UnauthCode)
	w.Write([]byte(da.Headers.V().UnauthResponse))
	da.mutex.RUnlock()
}
func DigestAuthParams(authorization string) map[string]string {
	s := strings.SplitN(authorization, " ", 2)
	if len(s) != 2 || s[0] != "Digest" {
		return nil
	}
	return ParsePairs(s[1])
}
func (da *DigestAuth) CheckAuth(r *http.Request) (username string, authinfo *string) {
	da.mutex.RLock()
	defer da.mutex.RUnlock()
	username = ""
	authinfo = nil
	auth := DigestAuthParams(r.Header.Get(da.Headers.V().Authorization))
	if auth == nil {
		return "", nil
	}
	if _, ok := auth["algorithm"]; !ok {
		auth["algorithm"] = "MD5"
	}
	if da.Opaque != auth["opaque"] || auth["algorithm"] != "MD5" || auth["qop"] != "auth" {
		return "", nil
	}
	if r.RequestURI != auth["uri"] {
		switch u, err := url.Parse(auth["uri"]); {
		case err != nil:
			return "", nil
		case r.URL == nil:
			return "", nil
		case len(u.Path) > len(r.URL.Path):
			return "", nil
		case !strings.HasPrefix(r.URL.Path, u.Path):
			return "", nil
		}
	}
	HA1 := da.Secrets(auth["username"], da.Realm)
	if da.PlainTextSecrets {
		HA1 = H(auth["username"] + ":" + da.Realm + ":" + HA1)
	}
	HA2 := H(r.Method + ":" + auth["uri"])
	KD := H(strings.Join([]string{HA1, auth["nonce"], auth["nc"], auth["cnonce"], auth["qop"], HA2}, ":"))
	if subtle.ConstantTimeCompare([]byte(KD), []byte(auth["response"])) != 1 {
		return "", nil
	}
	nc, err := strconv.ParseUint(auth["nc"], 16, 64)
	if err != nil {
		return "", nil
	}
	client, ok := da.clients[auth["nonce"]]
	if !ok {
		return "", nil
	}
	if client.nc != 0 && client.nc >= nc && !da.IgnoreNonceCount {
		return "", nil
	}
	client.nc = nc
	client.lastSeen = time.Now().UnixNano()
	respHA2 := H(":" + auth["uri"])
	rspauth := H(strings.Join([]string{HA1, auth["nonce"], auth["nc"], auth["cnonce"], auth["qop"], respHA2}, ":"))
	info := fmt.Sprintf(`qop="auth", rspauth="%s", cnonce="%s", nc="%s"`, rspauth, auth["cnonce"], auth["nc"])
	return auth["username"], &info
}
const (
	DefaultClientCacheSize      = 1000
	DefaultClientCacheTolerance = 100
)
func (da *DigestAuth) Wrap(wrapped AuthenticatedHandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if username, authinfo := da.CheckAuth(r); username == "" {
			da.RequireAuth(w, r)
		} else {
			ar := &AuthenticatedRequest{Request: *r, Username: username}
			if authinfo != nil {
				w.Header().Set(da.Headers.V().AuthInfo, *authinfo)
			}
			wrapped(w, ar)
		}
	}
}
func (da *DigestAuth) JustCheck(wrapped http.HandlerFunc) http.HandlerFunc {
	return da.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) {
		ar.Header.Set(AuthUsernameHeader, ar.Username)
		wrapped(w, &ar.Request)
	})
}
func (da *DigestAuth) NewContext(ctx context.Context, r *http.Request) context.Context {
	username, authinfo := da.CheckAuth(r)
	da.mutex.Lock()
	defer da.mutex.Unlock()
	info := &Info{Username: username, ResponseHeaders: make(http.Header)}
	if username != "" {
		info.Authenticated = true
		info.ResponseHeaders.Set(da.Headers.V().AuthInfo, *authinfo)
	} else {
		if len(da.clients) > da.ClientCacheSize+da.ClientCacheTolerance {
			da.purgeLocked(da.ClientCacheTolerance * 2)
		}
		nonce := RandomKey()
		da.clients[nonce] = &digestClient{nc: 0, lastSeen: time.Now().UnixNano()}
		info.ResponseHeaders.Set(da.Headers.V().Authenticate,
			fmt.Sprintf(`Digest realm="%s", nonce="%s", opaque="%s", algorithm=MD5, qop="auth"`,
				da.Realm, nonce, da.Opaque))
	}
	return context.WithValue(ctx, infoKey, info)
}