-
Notifications
You must be signed in to change notification settings - Fork 13
/
hmac_test.go
102 lines (92 loc) · 2.5 KB
/
hmac_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package openssl_test
import (
"bytes"
"hash"
"testing"
"github.com/golang-fips/openssl/v2"
)
func TestHMAC(t *testing.T) {
var tests = []struct {
name string
fn func() hash.Hash
}{
{"sha1", openssl.NewSHA1},
{"sha224", openssl.NewSHA224},
{"sha256", openssl.NewSHA256},
{"sha384", openssl.NewSHA384},
{"sha512", openssl.NewSHA512},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
h := openssl.NewHMAC(tt.fn, nil)
if h == nil {
t.Skip("digest not supported")
}
h.Write([]byte("hello"))
sumHello := h.Sum(nil)
h = openssl.NewHMAC(tt.fn, nil)
h.Write([]byte("hello world"))
sumHelloWorld := h.Sum(nil)
// Test that Sum has no effect on future Sum or Write operations.
// This is a bit unusual as far as usage, but it's allowed
// by the definition of Go hash.Hash, and some clients expect it to work.
h = openssl.NewHMAC(tt.fn, nil)
h.Write([]byte("hello"))
if sum := h.Sum(nil); !bytes.Equal(sum, sumHello) {
t.Fatalf("1st Sum after hello = %x, want %x", sum, sumHello)
}
if sum := h.Sum(nil); !bytes.Equal(sum, sumHello) {
t.Fatalf("2nd Sum after hello = %x, want %x", sum, sumHello)
}
h.Write([]byte(" world"))
if sum := h.Sum(nil); !bytes.Equal(sum, sumHelloWorld) {
t.Fatalf("1st Sum after hello world = %x, want %x", sum, sumHelloWorld)
}
if sum := h.Sum(nil); !bytes.Equal(sum, sumHelloWorld) {
t.Fatalf("2nd Sum after hello world = %x, want %x", sum, sumHelloWorld)
}
h.Reset()
h.Write([]byte("hello"))
if sum := h.Sum(nil); !bytes.Equal(sum, sumHello) {
t.Fatalf("Sum after Reset + hello = %x, want %x", sum, sumHello)
}
})
}
}
func TestHMACUnsupportedHash(t *testing.T) {
// Test that NewHMAC returns nil for unsupported hashes
// instead of panicking.
h := openssl.NewHMAC(newStubHash, nil)
if h != nil {
t.Errorf("returned non-nil for unsupported hash")
}
}
func BenchmarkHMACSHA256_32(b *testing.B) {
b.StopTimer()
key := make([]byte, 32)
buf := make([]byte, 32)
h := openssl.NewHMAC(openssl.NewSHA256, key)
b.SetBytes(int64(len(buf)))
b.StartTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
h.Write(buf)
mac := h.Sum(nil)
h.Reset()
buf[0] = mac[0]
}
}
func BenchmarkHMACNewWriteSum(b *testing.B) {
b.StopTimer()
buf := make([]byte, 32)
b.SetBytes(int64(len(buf)))
b.StartTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
h := openssl.NewHMAC(openssl.NewSHA256, make([]byte, 32))
h.Write(buf)
mac := h.Sum(nil)
buf[0] = mac[0]
}
}