11package hmac
22
33import (
4- "bytes"
54 "crypto/hmac"
65 "encoding/base64"
76 "encoding/binary"
87 "hash"
98 "time"
9+ "unsafe"
1010)
1111
1212const (
@@ -16,25 +16,26 @@ const (
1616
1717var hmacSignaturePrefix = []byte (HMACSignaturePrefix )
1818
19- type HMACToken struct {
20- Expire int64
21- Signature [HMACSignatureSize ]byte
22- }
23-
2419func 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
4041func CalculateHMACSignature (mac hash.Hash , username []byte , expire int64 ) []byte {
0 commit comments