-
Notifications
You must be signed in to change notification settings - Fork 208
/
one_time_token_generator.go
68 lines (54 loc) · 2.16 KB
/
one_time_token_generator.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
package authboss
import (
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"io"
)
// OneTimeTokenGenerator is an interface for generating one-time tokens
// for authentication purposes.
type OneTimeTokenGenerator interface {
// Generatetoken generates a one-time use 2-part token for authenticating a request.
// selector: to be stored in the database and ALWAYS used in select query
// verifier: to be stored in database but NEVER used in select query
// token: the user-facing base64 encoded selector+verifier
GenerateToken() (selector, verifier, token string, err error)
ParseToken(token string) (selectorBytes, verifierBytes []byte)
TokenSize() int
}
const (
tokenSize = 64
tokenSplit = tokenSize / 2
)
// Sha512TokenGenerator generates one-time tokens using SHA512
type Sha512TokenGenerator struct{}
// NewSha512TokenGenerator creates a new Sha512TokenGenerator
func NewSha512TokenGenerator() *Sha512TokenGenerator {
return &Sha512TokenGenerator{}
}
// GenerateToken generates pieces needed as credentials
// selector: hash of the first half of an N byte value
// (to be stored in the database and used in SELECT query)
// verifier: hash of the second half of an N byte value
// (to be stored in database but never used in SELECT query)
// token: the user-facing base64 encoded selector+verifier
func (cg *Sha512TokenGenerator) GenerateToken() (selector, verifier, token string, err error) {
rawToken := make([]byte, tokenSize)
if _, err = io.ReadFull(rand.Reader, rawToken); err != nil {
return "", "", "", err
}
selectorBytes := sha512.Sum512(rawToken[:tokenSplit])
verifierBytes := sha512.Sum512(rawToken[tokenSplit:])
return base64.StdEncoding.EncodeToString(selectorBytes[:]),
base64.StdEncoding.EncodeToString(verifierBytes[:]),
base64.URLEncoding.EncodeToString(rawToken),
nil
}
func (cg *Sha512TokenGenerator) ParseToken(rawToken string) (selectorBytes, verifierBytes []byte) {
selectorBytes64 := sha512.Sum512([]byte(rawToken)[:tokenSplit])
selectorBytes = selectorBytes64[:]
verifierBytes64 := sha512.Sum512([]byte(rawToken)[tokenSplit:])
verifierBytes = verifierBytes64[:]
return
}
func (cg *Sha512TokenGenerator) TokenSize() int { return tokenSize }