-
Notifications
You must be signed in to change notification settings - Fork 13
/
encrypt.go
92 lines (80 loc) · 1.87 KB
/
encrypt.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
package fasthttpsession
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/json"
)
// fasthttpsession encrypt tool
// - json
// - gob
// - base64
const (
BASE64TABLE = "1234567890poiuytreqwasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM-_"
)
func NewEncrypt() *encrypt {
return &encrypt{}
}
type encrypt struct {
}
// json encode
func (s *encrypt) JsonEncode(data map[string]interface{}) ([]byte, error) {
return json.Marshal(data)
}
// json decode
func (s *encrypt) JsonDecode(data []byte) (map[string]interface{}, error) {
tempValue := make(map[string]interface{})
err := json.Unmarshal(data, &tempValue)
if err != nil {
return tempValue, err
}
return tempValue, nil
}
// gob encode
func (s *encrypt) GobEncode(data map[string]interface{}) ([]byte, error) {
if len(data) == 0 {
return []byte(""), nil
}
for _, v := range data {
gob.Register(v)
}
buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf)
err := enc.Encode(data)
if err != nil {
return []byte(""), err
}
return buf.Bytes(), nil
}
// gob decode data to map
func (s *encrypt) GobDecode(data []byte) (map[string]interface{}, error) {
if len(data) == 0 {
return make(map[string]interface{}), nil
}
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
var out map[string]interface{}
err := dec.Decode(&out)
if err != nil {
return make(map[string]interface{}), err
}
return out, nil
}
// base64 encode
func (s *encrypt) Base64Encode(data map[string]interface{}) ([]byte, error) {
var coder = base64.NewEncoding(BASE64TABLE)
b, err := s.GobEncode(data)
if err != nil {
return []byte{}, err
}
return []byte(coder.EncodeToString(b)), nil
}
// base64 decode
func (s *encrypt) Base64Decode(data []byte) (map[string]interface{}, error) {
var coder = base64.NewEncoding(BASE64TABLE)
b, err := coder.DecodeString(string(data))
if err != nil {
return nil, err
}
return s.GobDecode(b)
}