forked from cmcoffee/go-kvlite
/
data.go
executable file
·73 lines (53 loc) · 1.45 KB
/
data.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
package kvlite
import (
"crypto/aes"
"crypto/sha256"
"crypto/rand"
"math/big"
"crypto/cipher"
"encoding/base64"
)
// Perform sha256.Sum256 against input byte string.
func hashBytes(input []byte) []byte {
sum := sha256.Sum256(input)
var output []byte
output = append(output[0:], sum[0:]...)
return output
}
// Generates a random byte slice of length specified.
func randBytes(sz int) []byte {
if sz <= 0 { sz = 16 }
ch := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/="
chlen := len(ch)
rand_string := make([]byte, sz)
rand.Read(rand_string)
for i, v := range rand_string {
rand_string[i] = ch[v%byte(chlen)]
}
return rand_string
}
// Generates a random integer of 0-max.
func randInt(max int) int {
maxBig := *big.NewInt(int64(max))
output, _ := rand.Int(rand.Reader, &maxBig)
return int(output.Int64())
}
func encrypt(input []byte, key []byte) []byte {
var (
block cipher.Block
)
key = hashBytes(key)
block, _ = aes.NewCipher(key)
buff := make([]byte, len(input))
copy(buff, input)
cipher.NewCFBEncrypter(block, key[0:block.BlockSize()]).XORKeyStream(buff, buff)
return []byte(base64.StdEncoding.EncodeToString(buff))
}
func decrypt(input []byte, key []byte) (decoded []byte) {
var block cipher.Block
key = hashBytes(key)
decoded, _ = base64.StdEncoding.DecodeString(string(input))
block, _ = aes.NewCipher(key)
cipher.NewCFBDecrypter(block, key[0:block.BlockSize()]).XORKeyStream(decoded, decoded)
return
}