forked from justinas/nosurf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
48 lines (38 loc) · 854 Bytes
/
crypto.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
package csrf
import (
"crypto/rand"
"io"
)
// Slices must be of the same length, or oneTimePad will panic
func oneTimePad(data, key []byte) {
n := len(data)
if n != len(key) {
panic("Lengths of slices are not equal")
}
for i := 0; i < n; i++ {
data[i] ^= key[i]
}
}
func maskToken(data []byte) []byte {
if len(data) != tokenLength {
return nil
}
result := make([]byte, 2*tokenLength)
key := result[:tokenLength]
token := result[tokenLength:]
copy(token, data)
// generate the random token
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
}
oneTimePad(token, key)
return result
}
func unmaskToken(data []byte) []byte {
if len(data) != tokenLength*2 {
return nil
}
token := data[tokenLength:]
oneTimePad(token, data[:tokenLength])
return token
}