Skip to content

Commit a3afdd3

Browse files
committed
reuse HMAC hasher
1 parent f3cf718 commit a3afdd3

2 files changed

Lines changed: 10 additions & 6 deletions

File tree

handler/handler.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package handler
33
import (
44
"bufio"
55
"bytes"
6+
chmac "crypto/hmac"
7+
"crypto/sha256"
68
"fmt"
79
"io"
810

@@ -28,6 +30,8 @@ func (a *BasicHMACAuthHandler) Run(input io.Reader, output io.Writer) error {
2830
rd := bufio.NewReaderSize(input, bufSize)
2931
scanner := proto.NewElasticLineScanner(rd, '\n')
3032

33+
mac := chmac.New(sha256.New, a.Secret)
34+
3135
for scanner.Scan() {
3236
parts := bytes.SplitN(scanner.Bytes(), []byte{' '}, 4)
3337
if len(parts) < 3 {
@@ -38,7 +42,7 @@ func (a *BasicHMACAuthHandler) Run(input io.Reader, output io.Writer) error {
3842
username := proto.RFC1738Unescape(parts[1])
3943
password := proto.RFC1738Unescape(parts[2])
4044

41-
if hmac.VerifyHMACLoginAndPassword(a.Secret, username, password) {
45+
if hmac.VerifyHMACLoginAndPassword(mac, username, password) {
4246
fmt.Fprintf(output, "%s OK\n", channelID)
4347
} else {
4448
fmt.Fprintf(output, "%s ERR\n", channelID)

hmac/hmac.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ package hmac
33
import (
44
"bytes"
55
"crypto/hmac"
6-
"crypto/sha256"
76
"encoding/base64"
87
"encoding/binary"
8+
"hash"
99
"time"
1010
)
1111

@@ -21,7 +21,7 @@ type HMACToken struct {
2121
Signature [HMACSignatureSize]byte
2222
}
2323

24-
func VerifyHMACLoginAndPassword(secret, login, password []byte) bool {
24+
func VerifyHMACLoginAndPassword(mac hash.Hash, login, password []byte) bool {
2525
rd := base64.NewDecoder(base64.RawURLEncoding, bytes.NewReader(password))
2626

2727
var token HMACToken
@@ -33,12 +33,12 @@ func VerifyHMACLoginAndPassword(secret, login, password []byte) bool {
3333
return false
3434
}
3535

36-
expectedMAC := CalculateHMACSignature(secret, login, token.Expire)
36+
expectedMAC := CalculateHMACSignature(mac, login, token.Expire)
3737
return hmac.Equal(token.Signature[:], expectedMAC)
3838
}
3939

40-
func CalculateHMACSignature(secret, username []byte, expire int64) []byte {
41-
mac := hmac.New(sha256.New, secret)
40+
func CalculateHMACSignature(mac hash.Hash, username []byte, expire int64) []byte {
41+
mac.Reset()
4242
mac.Write(hmacSignaturePrefix)
4343
mac.Write(username)
4444
binary.Write(mac, binary.BigEndian, expire)

0 commit comments

Comments
 (0)