forked from justinas/nosurf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
72 lines (57 loc) · 1.67 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package nosurf
import (
"crypto/rand"
"crypto/sha256"
"io"
)
const (
keyLength = 32 // Length of the derived key from the password
)
var MaskPassword = []byte("yoursuperpasswordhere!")
// DeriveKeyFromPassword derives a key from the provided password.
func deriveKeyFromPassword(password []byte) []byte {
hashed := sha256.Sum256(password)
return hashed[:]
}
// oneTimePad encrypts/decrypts the data using the given key.
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]
}
}
// Masks/unmasks the given data *in place*
// with the given key
// Slices must be of the same length, or oneTimePad will panic
func maskToken(data []byte) []byte {
//log.Println("maskToken start", len(data), data)
if len(data) != tokenLength {
return nil
}
key := deriveKeyFromPassword(MaskPassword)
result := make([]byte, 2*tokenLength)
copy(result[tokenLength:], data)
if _, err := io.ReadFull(rand.Reader, result[:tokenLength]); err != nil {
panic(err)
}
//log.Println("maskToken oneTimePad", len(result[tokenLength:]), result[tokenLength:], len(key), key)
oneTimePad(result[tokenLength:], key)
//log.Println("maskToken result", len(result), result)
return result
}
// unmaskToken unmasks a token using a password.
func unmaskToken(data []byte) []byte {
//log.Println("unmaskToken start", len(data), data)
if len(data) != tokenLength*2 {
return nil
}
key := deriveKeyFromPassword(MaskPassword)
token := data[tokenLength:]
//log.Println("unmaskToken token", len(token), token)
oneTimePad(token, key)
//log.Println("unmaskToken end", len(token), token)
return token
}