Skip to content

Commit 5970b9e

Browse files
committed
hmac: get rid of decoder allocations and binary reader reflection
1 parent a3afdd3 commit 5970b9e

1 file changed

Lines changed: 13 additions & 12 deletions

File tree

hmac/hmac.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package hmac
22

33
import (
4-
"bytes"
54
"crypto/hmac"
65
"encoding/base64"
76
"encoding/binary"
87
"hash"
98
"time"
9+
"unsafe"
1010
)
1111

1212
const (
@@ -16,25 +16,26 @@ const (
1616

1717
var hmacSignaturePrefix = []byte(HMACSignaturePrefix)
1818

19-
type HMACToken struct {
20-
Expire int64
21-
Signature [HMACSignatureSize]byte
22-
}
23-
2419
func VerifyHMACLoginAndPassword(mac hash.Hash, login, password []byte) bool {
25-
rd := base64.NewDecoder(base64.RawURLEncoding, bytes.NewReader(password))
20+
n, err := base64.RawURLEncoding.Decode(password, password)
21+
if err != nil {
22+
return false
23+
}
24+
password = password[:n]
2625

27-
var token HMACToken
28-
if err := binary.Read(rd, binary.BigEndian, &token); err != nil {
26+
var expire int64
27+
if len(password) < int(unsafe.Sizeof(expire)) {
2928
return false
3029
}
30+
expire = int64(binary.BigEndian.Uint64(password[:unsafe.Sizeof(expire)]))
31+
password = password[unsafe.Sizeof(expire):]
3132

32-
if time.Unix(token.Expire, 0).Before(time.Now()) {
33+
if time.Unix(expire, 0).Before(time.Now()) {
3334
return false
3435
}
3536

36-
expectedMAC := CalculateHMACSignature(mac, login, token.Expire)
37-
return hmac.Equal(token.Signature[:], expectedMAC)
37+
expectedMAC := CalculateHMACSignature(mac, login, expire)
38+
return hmac.Equal(password, expectedMAC)
3839
}
3940

4041
func CalculateHMACSignature(mac hash.Hash, username []byte, expire int64) []byte {

0 commit comments

Comments
 (0)