github.com/Tyktechnologies/tyk@v2.9.5+incompatible/signature_validator/validate.go (about)

     1  package signature_validator
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/hex"
     6  	"errors"
     7  	"fmt"
     8  	"time"
     9  )
    10  
    11  type Validator interface {
    12  	Init(hasherName string) error
    13  	Validate(attempt, actual string, allowedClockSkew int64) error
    14  }
    15  
    16  type SignatureValidator struct {
    17  	h Hasher
    18  }
    19  
    20  func (v *SignatureValidator) Init(hasherName string) error {
    21  	switch hasherName {
    22  	case "MasherySHA256":
    23  		v.h = MasherySha256Sum{}
    24  	case "MasheryMD5":
    25  		v.h = MasheryMd5sum{}
    26  	default:
    27  		return errors.New(fmt.Sprintf("unsupported hasher type (%s)", hasherName))
    28  	}
    29  
    30  	return nil
    31  }
    32  
    33  func (v SignatureValidator) Validate(signature, key, secret string, allowedClockSkew int64) error {
    34  	signatureBytes, _ := hex.DecodeString(signature)
    35  	now := time.Now().Unix()
    36  	for i := int64(0); i <= allowedClockSkew; i++ {
    37  		if bytes.Equal(v.h.Hash(key, secret, now+i), signatureBytes) {
    38  			return nil
    39  		}
    40  
    41  		if i == int64(0) {
    42  			continue
    43  		}
    44  
    45  		if bytes.Equal(v.h.Hash(key, secret, now-i), signatureBytes) {
    46  			return nil
    47  		}
    48  	}
    49  
    50  	return errors.New("signature is not valid")
    51  }