git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/jwt/hmac.go (about)

     1  package jwt
     2  
     3  import (
     4  	"crypto/hmac"
     5  	"crypto/subtle"
     6  	"hash"
     7  )
     8  
     9  func signTokenHMAC(hashFunction func() hash.Hash, secret, encodedHeaderAndClaims []byte) (signatureRaw []byte) {
    10  	hmac := hmac.New(hashFunction, secret)
    11  	hmac.Write(encodedHeaderAndClaims)
    12  	signatureRaw = hmac.Sum(nil)
    13  
    14  	return
    15  }
    16  
    17  func verifyTokenHMAC(hashFunction func() hash.Hash, secret, signature, encodedHeaderAndClaims []byte) (err error) {
    18  	hmac := hmac.New(hashFunction, secret)
    19  	hmac.Write(encodedHeaderAndClaims)
    20  	hmacHash := hmac.Sum(nil)
    21  
    22  	if subtle.ConstantTimeCompare(hmacHash, signature) != 1 {
    23  		err = ErrSignatureIsNotValid
    24  		return
    25  	}
    26  	return
    27  }