-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.go
346 lines (273 loc) · 8.84 KB
/
converter.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Package fst is a high-performance, low-memory library for generating and parsing Fast Signed Tokens (FST). FST provides an alternative to JSON-based tokens and allows you to store any information that can be represented as []byte. You can use FST for the same purposes as JWT.
package fst
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"github.com/Eugene-Usachev/fastbytes"
"hash"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
// Converter represents a token converter that can generate and parse Fast Signed Tokens.
//
// secretKey is the secret used to sign the token.
//
// postfix is the postfix to add to the token to more secure the token.
//
// hashType is the hash function used to sign the token.
//
// timeBeforeExpire is the lifetime of the token. By default, it is -1
//
// hmacPool and expirationTime and timeNow are needed to improve performance.
type Converter struct {
timeNow atomic.Int64
expirationTime atomic.Value
timeBeforeExpire time.Duration
secretKey []byte
postfix []byte
hmacPool sync.Pool
hashType hash.Hash
NewToken func([]byte) string
ParseToken func(string) ([]byte, error)
}
// ConverterConfig represents the configuration options for creating a new Converter.
//
// SecretKey is the secret used to sign the token.
//
// Postfix is the postfix to add to the token to more secure the token.
//
// ExpirationTime is the expiration time of the token. It is -1 by default and will not expire.
//
// HashType is the hash function used to sign the token.
type ConverterConfig struct {
// SecretKey is the secret used to sign the token.
SecretKey []byte
// Postfix is the postfix to add to the token to more secure the token.
Postfix []byte
// ExpirationTime is the expiration time of the token.
ExpirationTime time.Duration
// HashType is the hash function used to sign the token.
HashType func() hash.Hash
WithExpirationTime bool
}
// NewConverter creates a new instance of the Converter based on the provided fst.ConverterConfig.
//
// Example of the usage:
//
// converter := fst.NewConverter(&fst.ConverterConfig{
// SecretKey: []byte(`secret`),
// Postfix: nil,
// ExpirationTime: time.Minute * 5,
// HashType: sha256.New,
// DisableLogs: false,
// })
func NewConverter(cfg *ConverterConfig) *Converter {
if !cfg.WithExpirationTime {
cfg.ExpirationTime = -1
}
if cfg.HashType == nil {
cfg.HashType = sha256.New
}
converter := &Converter{
secretKey: cfg.SecretKey,
postfix: cfg.Postfix,
timeBeforeExpire: cfg.ExpirationTime,
hmacPool: sync.Pool{
New: func() interface{} {
return hmac.New(cfg.HashType, cfg.SecretKey)
},
},
}
if cfg.ExpirationTime != -1 {
if cfg.Postfix == nil {
converter.NewToken = converter.newTokenWithExpire
converter.ParseToken = converter.parseTokenWithExpire
} else {
converter.NewToken = converter.newTokenWithExpireAndPostfix
converter.ParseToken = converter.parseTokenWithExpireAndPostfix
}
converter.timeNow.Store(time.Now().Unix())
converter.expirationTime.Store(strconv.FormatInt(time.Now().Add(converter.timeBeforeExpire).Unix(), 10))
go func() {
var ex64 int64
for {
time.Sleep(1 * time.Second)
converter.timeNow.Add(1)
ex64, _ = strconv.ParseInt(converter.expirationTime.Load().(string), 10, 64)
ex64++
converter.expirationTime.Store(strconv.FormatInt(ex64, 10))
}
}()
} else {
if cfg.Postfix == nil {
converter.NewToken = converter.newToken
converter.ParseToken = converter.parseToken
} else {
converter.NewToken = converter.newTokenWithPostfix
converter.ParseToken = converter.parseTokenWithPostfix
}
}
return converter
}
func (c *Converter) newToken(value []byte) string {
// Create the payload
payloadBase64 := base64.RawURLEncoding.EncodeToString(value)
// Create the signature
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(fastbytes.S2B(payloadBase64))
signature := mac.Sum(nil)
c.hmacPool.Put(mac)
signatureBase64 := base64.RawURLEncoding.EncodeToString(signature)
return strings.Join([]string{payloadBase64, signatureBase64}, ".")
}
func (c *Converter) newTokenWithExpire(value []byte) string {
// Create the payload
payloadBase64 := base64.RawURLEncoding.EncodeToString(value)
exTime := c.expirationTime.Load().(string)
// Create the signature
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(fastbytes.S2B(payloadBase64 + exTime))
signature := mac.Sum(nil)
c.hmacPool.Put(mac)
signatureBase64 := base64.RawURLEncoding.EncodeToString(signature)
return strings.Join([]string{payloadBase64, signatureBase64, exTime}, ".")
}
func (c *Converter) newTokenWithPostfix(value []byte) string {
// Create the payload
payloadBase64 := base64.RawURLEncoding.EncodeToString(value)
// Create the signature
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(append(fastbytes.S2B(payloadBase64), c.postfix...))
signature := mac.Sum(nil)
c.hmacPool.Put(mac)
signatureBase64 := base64.RawURLEncoding.EncodeToString(signature)
return strings.Join([]string{payloadBase64, signatureBase64}, ".")
}
func (c *Converter) newTokenWithExpireAndPostfix(value []byte) string {
// Create the payload
payloadBase64 := base64.RawURLEncoding.EncodeToString(value)
exTime := c.expirationTime.Load().(string)
// Create the signature
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(append(fastbytes.S2B(payloadBase64+exTime), c.postfix...))
signature := mac.Sum(nil)
c.hmacPool.Put(mac)
signatureBase64 := base64.RawURLEncoding.EncodeToString(signature)
return strings.Join([]string{payloadBase64, signatureBase64, exTime}, ".")
}
var (
InvalidTokenFormat = errors.New("Invalid token format")
InvalidSignature = errors.New("Invalid signature")
TokenExpired = errors.New("Token expired")
)
func (c *Converter) parseToken(token string) ([]byte, error) {
components := strings.Split(token, ".")
if len(components) != 2 {
return nil, InvalidTokenFormat
}
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(fastbytes.S2B(components[0]))
expectedSignature, err := base64.RawURLEncoding.DecodeString(components[1])
if err != nil {
return nil, err
}
actualSignature := mac.Sum(nil)
c.hmacPool.Put(mac)
if !hmac.Equal(expectedSignature, actualSignature) {
return nil, InvalidSignature
}
return base64.RawURLEncoding.DecodeString(components[0])
}
func (c *Converter) parseTokenWithExpire(token string) ([]byte, error) {
components := strings.Split(token, ".")
if len(components) != 3 {
return nil, InvalidTokenFormat
}
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(fastbytes.S2B(components[0] + components[2]))
expectedSignature, err := base64.RawURLEncoding.DecodeString(components[1])
if err != nil {
return nil, err
}
actualSignature := mac.Sum(nil)
c.hmacPool.Put(mac)
if !hmac.Equal(expectedSignature, actualSignature) {
return nil, InvalidSignature
}
expiration, err := strconv.ParseInt(components[2], 10, 64)
if err != nil {
return nil, err
}
if c.timeNow.Load() > expiration {
return nil, TokenExpired
}
return base64.RawURLEncoding.DecodeString(components[0])
}
func (c *Converter) parseTokenWithPostfix(token string) ([]byte, error) {
components := strings.Split(token, ".")
if len(components) != 2 {
return nil, InvalidTokenFormat
}
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(append(fastbytes.S2B(components[0]), c.postfix...))
expectedSignature, err := base64.RawURLEncoding.DecodeString(components[1])
if err != nil {
return nil, err
}
actualSignature := mac.Sum(nil)
c.hmacPool.Put(mac)
if !hmac.Equal(expectedSignature, actualSignature) {
return nil, InvalidSignature
}
return base64.RawURLEncoding.DecodeString(components[0])
}
func (c *Converter) parseTokenWithExpireAndPostfix(token string) ([]byte, error) {
components := strings.Split(token, ".")
if len(components) != 3 {
return nil, InvalidTokenFormat
}
mac := c.hmacPool.Get().(hash.Hash)
mac.Reset()
mac.Write(append(fastbytes.S2B(components[0]+components[2]), c.postfix...))
expectedSignature, err := base64.RawURLEncoding.DecodeString(components[1])
if err != nil {
return nil, err
}
actualSignature := mac.Sum(nil)
c.hmacPool.Put(mac)
if !hmac.Equal(expectedSignature, actualSignature) {
return nil, InvalidSignature
}
expiration, err := strconv.ParseInt(components[2], 10, 64)
if err != nil {
return nil, err
}
if c.timeNow.Load() > expiration {
return nil, TokenExpired
}
return base64.RawURLEncoding.DecodeString(components[0])
}
// SecretKey returns the secret key used by the Converter.
func (c *Converter) SecretKey() []byte {
return c.secretKey
}
// Postfix returns the postfix used by the Converter.
func (c *Converter) Postfix() []byte {
return c.postfix
}
// ExpireTime returns the expiration time used by the Converter.
func (c *Converter) ExpireTime() time.Duration {
return c.timeBeforeExpire
}