forked from cbonello/revel-csrf
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tokengen.go
43 lines (35 loc) · 967 Bytes
/
tokengen.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
package csrf
import (
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
const (
rawTokenLength = 32
)
var (
tokenLength = base64.StdEncoding.EncodedLen(rawTokenLength)
)
// A token is generated by reading rawTokenLength bytes
// from crypto/rand and encoding that as base64.
func generateToken() string {
bytes := make([]byte, rawTokenLength)
_, _ = io.ReadFull(rand.Reader, bytes)
// I'm not sure how to handle the error from the above call.
// It shouldn't EVER really happen,
// as we check for the availablity of crypto/random
// in the init() function
// and both /dev/urandom and CryptGenRandom()
// should be inexhaustible.
return base64.StdEncoding.EncodeToString(bytes)
}
func init() {
// Check that cryptographically secure PRNG is available
// In case it's not, panic.
buf := make([]byte, 1)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
panic(fmt.Sprintf("crypto/rand is unavailable: Read() failed with %#v", err))
}
}