-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
267 lines (238 loc) · 5.17 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package common
import (
"bytes"
"compress/zlib"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"hash/fnv"
"io"
"io/ioutil"
"math/big"
mathrand "math/rand"
"os"
"runtime"
"sort"
"sync"
)
var (
Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
GCMNonce NonceGenerator = NewNonceGenerator(12)
)
func EncryptString(secret string, data string) (string, error) {
d, err := compress([]byte(data))
if err != nil {
return "", err
}
d, err = encrypt([]byte(secret), d)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(d), nil
}
func DecryptString(secret string, data string) (string, error) {
d, err := base64.URLEncoding.DecodeString(data)
if err != nil {
return "", err
}
d, err = decrypt([]byte(secret), d)
if err != nil {
return "", err
}
d, err = decompress(d)
if err != nil {
return "", err
}
return string(d), nil
}
func Hash(str string, n int) string {
hasher := sha256.New()
hasher.Write([]byte(str))
return hashSize(hasher.Sum(nil), n)
}
func QuickHash(str string, n int) string {
hasher := fnv.New64()
hasher.Write([]byte(str))
return hashSize(hasher.Sum(nil), n)
}
func HashStream(r io.Reader, n int) string {
hasher := sha256.New()
io.Copy(hasher, r)
h := hex.EncodeToString(hasher.Sum(nil))
if n == 0 {
return h
} else if n >= len(h) {
return h
}
return h[0:n]
}
func hashSize(b []byte, n int) string {
h := ""
for i := 0; i < len(b); i++ {
if n > 0 && len(h) >= n {
break
}
h += ReversedBaseChange(Letters, int(b[i]))
}
if len(h) > n {
return h[0 : len(h)-1]
}
return h
}
func ReversedBaseChange(alphabet []rune, i int) string {
str := ""
for {
str += string(alphabet[i%len(alphabet)])
i = i / len(alphabet)
if i == 0 {
break
}
}
return str
}
func RandomString(n int) string {
b := make([]rune, n)
for i := range b {
max := *big.NewInt(int64(len(Letters)))
r, err := rand.Int(rand.Reader, &max)
if err != nil {
b[i] = Letters[0]
} else {
b[i] = Letters[r.Int64()]
}
}
return string(b)
}
func QuickString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = Letters[mathrand.Intn(len(Letters))]
}
return string(b)
}
func encrypt(key []byte, plaintext []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := GCMNonce.Next()
if gcm.NonceSize() != len(nonce) {
Log.Error("common::crypto nonce size isn't '12' but '%d'", gcm.NonceSize())
return nil, ErrNotValid
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func decrypt(key []byte, ciphertext []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, NewError("ciphertext too short", 500)
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}
func compress(something []byte) ([]byte, error) {
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write(something)
w.Close()
return b.Bytes(), nil
}
func decompress(something []byte) ([]byte, error) {
b := bytes.NewBuffer(something)
r, err := zlib.NewReader(b)
if err != nil {
return []byte(""), nil
}
r.Close()
return ioutil.ReadAll(r)
}
func sign(something []byte) ([]byte, error) {
return something, nil
}
func verify(something []byte) ([]byte, error) {
return something, nil
}
// Create a unique ID that can be use to identify different session
func GenerateID(ctx *App) string {
p := ""
orderedKeys := make([]string, len(ctx.Session))
for key, _ := range ctx.Session {
orderedKeys = append(orderedKeys, key)
}
sort.Strings(orderedKeys)
for _, key := range orderedKeys {
switch key {
case "timestamp":
case "password":
case "path":
default:
if val := ctx.Session[key]; val != "" {
p += key + "=>" + ctx.Session[key] + ", "
}
}
}
if p == "" {
return "na"
}
p += "salt=>" + SECRET_KEY
return Hash(p, 20)
}
// Create an ID that identify a machine
func GenerateMachineID() string {
if runtime.GOOS == "linux" {
if f, err := os.OpenFile("/etc/machine-id", os.O_RDONLY, os.ModePerm); err == nil {
defer f.Close()
b := make([]byte, 32)
if _, err = f.Read(b); err == nil {
return string(b)
}
} else if f, err := os.OpenFile("/var/lib/dbus/machine-id", os.O_RDONLY, os.ModePerm); err == nil {
defer f.Close()
b := make([]byte, 32)
if _, err = f.Read(b); err == nil {
return string(b)
}
}
}
return "na"
}
type NonceGenerator struct {
current []byte
count int
*sync.Mutex
}
func NewNonceGenerator(size int) NonceGenerator {
firstNonce := make([]byte, size)
io.ReadFull(rand.Reader, firstNonce)
var m sync.Mutex
return NonceGenerator{firstNonce, size, &m}
}
func (this *NonceGenerator) Next() []byte {
this.Lock()
newNonce := make([]byte, this.count)
for i := len(this.current) - 1; i >= 0; i-- {
if this.current[i] < 255 {
this.current[i] += 1
break
}
this.current[i] = 0
}
newNonce = this.current
this.Unlock()
return newNonce
}