diff --git a/mac/subtle/hmac.go b/mac/subtle/hmac.go index 1e335ed..d9cdf4e 100644 --- a/mac/subtle/hmac.go +++ b/mac/subtle/hmac.go @@ -82,10 +82,11 @@ func ValidateHMACParams(hash string, keySize uint32, tagSize uint32) error { // ComputeMAC computes message authentication code (MAC) for the given data. func (h *HMAC) ComputeMAC(data []byte) ([]byte, error) { - mac := hmac.New(h.HashFunc, h.Key) - if _, err := mac.Write(data); err != nil { - return nil, err + if h.HashFunc == nil { + return nil, fmt.Errorf("hmac: invalid hash algorithm") } + mac := hmac.New(h.HashFunc, h.Key) + mac.Write(data) tag := mac.Sum(nil) return tag[:h.TagSize], nil } diff --git a/mac/subtle/hmac_test.go b/mac/subtle/hmac_test.go index 8cadd30..14a7faa 100644 --- a/mac/subtle/hmac_test.go +++ b/mac/subtle/hmac_test.go @@ -116,6 +116,20 @@ func TestNewHMACWithInvalidInput(t *testing.T) { } } +func TestHMACWithNilHashFunc(t *testing.T) { + cipher, err := subtle.NewHMAC("SHA256", random.GetRandomBytes(32), 32) + if err != nil { + t.Fatalf("subtle.NewHMAC() err = %v", err) + } + + // Modify exported field. + cipher.HashFunc = nil + + if _, err := cipher.ComputeMAC([]byte{}); err == nil { + t.Errorf("cipher.ComputerMAC() err = nil, want not nil") + } +} + func TestHMAComputeVerifyWithNilInput(t *testing.T) { cipher, err := subtle.NewHMAC("SHA256", random.GetRandomBytes(16), 32) if err != nil { diff --git a/subtle/subtle.go b/subtle/subtle.go index 797879b..14db405 100644 --- a/subtle/subtle.go +++ b/subtle/subtle.go @@ -124,12 +124,7 @@ func ComputeHash(hashFunc func() hash.Hash, data []byte) ([]byte, error) { return nil, errNilHashFunc } h := hashFunc() - - _, err := h.Write(data) - if err != nil { - return nil, err - } - + h.Write(data) return h.Sum(nil), nil }