Skip to content

Commit

Permalink
HMAC empty inputs without panicing
Browse files Browse the repository at this point in the history
re #7
  • Loading branch information
Richard Kettlewell authored and Richard Kettlewell committed Oct 3, 2018
1 parent 557645c commit b661a57
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
12 changes: 12 additions & 0 deletions hmac.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ type hmacImplementation struct {
// Cleanup function
cleanup func()

// Count of updates
updates uint64

// Result, or nil if we don't have the answer yet
result []byte
}
Expand Down Expand Up @@ -167,6 +170,7 @@ func (hi *hmacImplementation) initialize() (err error) {
hi.cleanup()
return
}
hi.updates = 0
hi.result = nil
return
}
Expand All @@ -181,13 +185,21 @@ func (hi *hmacImplementation) Write(p []byte) (n int, err error) {
if err = hi.session.Ctx.SignUpdate(hi.session.Handle, p); err != nil {
return
}
hi.updates++
n = len(p)
return
}

func (hi *hmacImplementation) Sum(b []byte) []byte {
if hi.result == nil {
var err error
if hi.updates == 0 {
// http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc322855304
// We must ensure that C_SignUpdate is called _at least once_.
if err = hi.session.Ctx.SignUpdate(hi.session.Handle, []byte{}); err != nil {
panic(err)
}
}
hi.result, err = hi.session.Ctx.SignFinal(hi.session.Handle)
hi.cleanup()
if err != nil {
Expand Down
23 changes: 23 additions & 0 deletions hmac_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ func testHmac(t *testing.T, keytype int, mech int, length int, xlength int, full
}
})
if full { // Independent of hash, only do these once
t.Run("Empty", func(t *testing.T) {
// Must be able to MAC empty inputs without panicing
var h1 hash.Hash
if h1, err = key.NewHMAC(mech, length); err != nil {
t.Errorf("key.NewHMAC: %v", err)
return
}
h1.Sum([]byte{})
})
t.Run("MultiSum", func(t *testing.T) {
input := []byte("a different short string")
var h1 hash.Hash
Expand Down Expand Up @@ -158,5 +167,19 @@ func testHmac(t *testing.T, keytype int, mech int, length int, xlength int, full
return
}
})
t.Run("ResetFast", func(t *testing.T) {
// Reset() immediately after creation should be safe
var h1 hash.Hash
if h1, err = key.NewHMAC(mech, length); err != nil {
t.Errorf("key.NewHMAC: %v", err)
return
}
h1.Reset()
if n, err := h1.Write([]byte{2}); err != nil || n != 1 {
t.Errorf("h1.Write: %v/%d", err, n)
return
}
h1.Sum([]byte{})
})
}
}

0 comments on commit b661a57

Please sign in to comment.