| 1 | package jose |
| 2 | |
| 3 | import ( |
| 4 | "crypto/hmac" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | ) |
| 8 | |
| 9 | func init() { |
| 10 | RegisterJws(&HmacUsingSha{keySizeBits: 256}) |
| 11 | RegisterJws(&HmacUsingSha{keySizeBits: 384}) |
| 12 | RegisterJws(&HmacUsingSha{keySizeBits: 512}) |
| 13 | } |
| 14 | |
| 15 | // HMAC with SHA signing algorithm implementation |
| 16 | type HmacUsingSha struct{ |
| 17 | keySizeBits int |
| 18 | } |
| 19 | |
| 20 | func (alg *HmacUsingSha) Name() string { |
| 21 | switch alg.keySizeBits { |
| 22 | case 256: return HS256 |
| 23 | case 384: return HS384 |
| 24 | default: return HS512 |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func (alg *HmacUsingSha) Verify(securedInput, signature []byte, key interface{}) error { |
| 29 | if privKey,ok:=key.([]byte); ok { |
| 30 | actualSig, err := alg.Sign(securedInput, privKey) |
| 31 | |
| 32 | if err != nil { |
| 33 | return fmt.Errorf("HmacUsingSha.Verify(): Signature validation failed: %w", err) |
| 34 | } |
| 35 | |
| 36 | if !hmac.Equal(signature, actualSig) { |
| 37 | return errors.New("HmacUsingSha.Verify(): Signature is invalid") |
| 38 | } |
| 39 | |
| 40 | return nil |
| 41 | } |
| 42 | |
| 43 | return errors.New("HmacUsingSha.Verify(): expects key to be '[]byte' array") |
| 44 | } |
| 45 | |
| 46 | func (alg *HmacUsingSha) Sign(securedInput []byte, key interface{}) (signature []byte, err error) { |
| 47 | //TODO: assert min key size |
| 48 | |
| 49 | if pubKey,ok:=key.([]byte); ok { |
| 50 | return calculateHmac(alg.keySizeBits, securedInput, pubKey),nil |
| 51 | } |
| 52 | |
| 53 | return nil,errors.New("HmacUsingSha.Sign(): expects key to be '[]byte' array") |
| 54 | } |