-
Notifications
You must be signed in to change notification settings - Fork 9
/
secure_token.go
38 lines (32 loc) · 1021 Bytes
/
secure_token.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
package session
import (
"crypto/rand"
"crypto/subtle"
"math/big"
mrand "math/rand"
"time"
)
// SecureToken generates a unique random token.
// Length should be 24 to match ActiveRecord::SecureToken used by the reference implementation.
func SecureToken(length int) string {
const base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
pass := make([]byte, length)
chars := []byte(base58)
mrand.New(mrand.NewSource(time.Now().UnixNano())).Shuffle(len(chars), func(i, j int) {
chars[i], chars[j] = chars[j], chars[i]
})
max := big.NewInt(int64(len(chars)))
for i := 0; i < length; i++ {
n, err := rand.Int(rand.Reader, max)
if err != nil {
panic(err) // should never occured because max >= 0
}
pass[i] = chars[int(n.Int64())]
}
return string(pass)
}
// SecureCompare compares the givens strings in a constant time.
// So length info is not leaked via timing attacks.
func SecureCompare(s1, s2 string) bool {
return subtle.ConstantTimeCompare([]byte(s1), []byte(s2)) == 1
}