Skip to content

Commit 5c33b3e

Browse files
committed
hmac auth: add benchmarks
1 parent ef9ff90 commit 5c33b3e

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

auth/hmac.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ type HMACToken struct {
6363
Signature [HMACSignatureSize]byte
6464
}
6565

66-
func (auth *HMACAuth) validateToken(login, password string) bool {
66+
func VerifyHMACLoginAndPassword(secret []byte, login, password string) bool {
6767
marshaledToken, err := base64.RawURLEncoding.DecodeString(password)
6868
if err != nil {
6969
return false
@@ -79,10 +79,14 @@ func (auth *HMACAuth) validateToken(login, password string) bool {
7979
return false
8080
}
8181

82-
expectedMAC := CalculateHMACSignature(auth.secret, login, token.Expire)
82+
expectedMAC := CalculateHMACSignature(secret, login, token.Expire)
8383
return hmac.Equal(token.Signature[:], expectedMAC)
8484
}
8585

86+
func (auth *HMACAuth) validateToken(login, password string) bool {
87+
return VerifyHMACLoginAndPassword(auth.secret, login, password)
88+
}
89+
8690
func (auth *HMACAuth) Validate(wr http.ResponseWriter, req *http.Request) (string, bool) {
8791
hdr := req.Header.Get("Proxy-Authorization")
8892
if hdr == "" {

auth/hmac_test.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package auth
2+
3+
import (
4+
"bytes"
5+
"crypto/rand"
6+
"encoding/base64"
7+
"encoding/binary"
8+
"testing"
9+
"time"
10+
)
11+
12+
var (
13+
resBytes []byte
14+
resBool bool
15+
)
16+
17+
func BenchmarkCalculateHMACSignature(b *testing.B) {
18+
var r []byte
19+
secret := make([]byte, HMACSignatureSize)
20+
if _, err := rand.Read(secret); err != nil {
21+
b.Fatalf("CSPRNG failure: %v", err)
22+
}
23+
b.ResetTimer()
24+
25+
for n := 0; n < b.N; n++ {
26+
r = CalculateHMACSignature(secret, "username", 0)
27+
}
28+
resBytes = r
29+
}
30+
31+
func BenchmarkVerifyHMACLoginAndPassword(b *testing.B) {
32+
var r bool
33+
secret := make([]byte, HMACSignatureSize)
34+
if _, err := rand.Read(secret); err != nil {
35+
b.Fatalf("CSPRNG failure: %v", err)
36+
}
37+
username := "username"
38+
expire := time.Now().Add(time.Hour).Unix()
39+
mac := CalculateHMACSignature(secret, username, expire)
40+
token := HMACToken{
41+
Expire: expire,
42+
}
43+
copy(token.Signature[:], mac)
44+
var resBuf bytes.Buffer
45+
enc := base64.NewEncoder(base64.RawURLEncoding, &resBuf)
46+
if err := binary.Write(enc, binary.BigEndian, &token); err != nil {
47+
b.Fatalf("token encoding failed: %v", err)
48+
}
49+
enc.Close()
50+
b.ResetTimer()
51+
52+
for n := 0; n < b.N; n++ {
53+
r = VerifyHMACLoginAndPassword(secret, username, resBuf.String())
54+
if !r {
55+
b.Fail()
56+
}
57+
}
58+
resBool = r
59+
}

0 commit comments

Comments
 (0)