File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ package csrf
2
+
3
+ import (
4
+ "crypto/rand"
5
+ "encoding/base64"
6
+ "fmt"
7
+ "io"
8
+ )
9
+
10
+ const (
11
+ rawTokenLength = 32
12
+ )
13
+
14
+ var (
15
+ tokenLength = base64 .StdEncoding .EncodedLen (rawTokenLength )
16
+ )
17
+
18
+ // A token is generated by reading rawTokenLength bytes
19
+ // from crypto/rand and encoding that as base64.
20
+ func generateToken () string {
21
+ bytes := make ([]byte , rawTokenLength )
22
+ _ , _ = io .ReadFull (rand .Reader , bytes )
23
+
24
+ // I'm not sure how to handle the error from the above call.
25
+ // It shouldn't EVER really happen,
26
+ // as we check for the availablity of crypto/random
27
+ // in the init() function
28
+ // and both /dev/urandom and CryptGenRandom()
29
+ // should be inexhaustible.
30
+
31
+ return base64 .StdEncoding .EncodeToString (bytes )
32
+ }
33
+
34
+ func init () {
35
+ // Check that cryptographically secure PRNG is available
36
+ // In case it's not, panic.
37
+ buf := make ([]byte , 1 )
38
+ _ , err := io .ReadFull (rand .Reader , buf )
39
+
40
+ if err != nil {
41
+ panic (fmt .Sprintf ("crypto/rand is unavailable: Read() failed with %#v" , err ))
42
+ }
43
+ }
You can’t perform that action at this time.
0 commit comments