-
Notifications
You must be signed in to change notification settings - Fork 372
/
crypto.go
105 lines (87 loc) · 2.32 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"io"
"github.com/flet-dev/flet/server/config"
)
// SHA1 returns SHA1 hash of the input string.
func SHA1(value string) string {
h := sha1.New()
io.WriteString(h, value)
return fmt.Sprintf("%x", h.Sum(nil))
}
func EncryptWithMasterKey(data []byte) ([]byte, error) {
return EncryptWithKey(data, config.MasterSecretKey())
}
func EncryptWithKey(data []byte, secretKey string) ([]byte, error) {
block, err := aes.NewCipher(GetCipherKey(secretKey))
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, aesgcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return aesgcm.Seal(nonce, nonce, data, nil), nil
}
func DecryptWithMasterKey(data []byte) ([]byte, error) {
return DecryptWithKey(data, config.MasterSecretKey())
}
func DecryptWithKey(cipherData []byte, secretKey string) ([]byte, error) {
block, err := aes.NewCipher(GetCipherKey(secretKey))
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesgcm.NonceSize()
if len(cipherData) < nonceSize {
return nil, errors.New("invalid cipher data")
}
nonce, ciphertext := cipherData[:nonceSize], cipherData[nonceSize:]
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func GetCipherKey(secretKey string) []byte {
key := make([]byte, 32)
for i, b := range []byte(secretKey)[:32] {
key[i] = b
}
return key
}
// source: https://github.com/gorilla/securecookie/blob/master/securecookie.go
func GenerateRandomKey(length int) []byte {
k := make([]byte, length)
if _, err := io.ReadFull(rand.Reader, k); err != nil {
return nil
}
return k
}
func EncodeBase64(value []byte) string {
encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))
base64.URLEncoding.Encode(encoded, value)
return string(encoded)
}
func DecodeBase64(value string) ([]byte, error) {
decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))
b, err := base64.URLEncoding.Decode(decoded, []byte(value))
if err != nil {
return nil, errors.New("base64 decode failed")
}
return decoded[:b], nil
}