-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathendecode.go
92 lines (86 loc) · 1.99 KB
/
endecode.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 endecode
import (
"golang.org/x/crypto/pbkdf2"
"crypto/sha1"
"sync"
"errors"
"reflect"
)
var mu sync.Mutex
type EnDeInfoEntity struct {
Crypt string
Key string
Salt string
}
type EnDeCode interface {
BlockCrypt
}
var endeCode EnDeCode
func Encode(dst []byte, endeInfo *EnDeInfoEntity) ([]byte, error) {
err := GetCrypt(endeInfo)
if(nil != err){
return nil,err
}
result :=endeCode.Encrypt(dst,dst)
return result,nil
}
func Decode(dst []byte, endeInfo *EnDeInfoEntity) ([]byte, error) {
err := GetCrypt(endeInfo)
if(nil != err){
return nil,err
}
result :=endeCode.Decrypt(dst,dst)
return result,nil
}
func GetCrypt(endeInfo *EnDeInfoEntity) (error) {
if (reflect.ValueOf(endeInfo).IsNil()) {
return errors.New("endeInfo is null")
}
//此处判断是因为如果已经有了可以不执行锁
if (endeCode != nil) {
return nil
}
mu.Lock()
defer mu.Unlock()
//再次判断,因为如果是多线程某些现场被卡死那么下面必须再次判断
if (endeCode != nil) {
return nil
}
pass := pbkdf2.Key([]byte(endeInfo.Key), []byte(endeInfo.Salt), 4096, 32, sha1.New)
var crypt EnDeCode
var err error
switch endeInfo.Crypt {
case "tea":
crypt, err = NewTEABlockCrypt(pass[:16])
case "xor":
crypt, err = NewSimpleXORBlockCrypt(pass)
case "none":
crypt, err = NewNoneBlockCrypt(pass)
case "aes-128":
crypt, err = NewAESBlockCrypt(pass[:16])
case "aes-192":
crypt, err = NewAESBlockCrypt(pass[:24])
case "blowfish":
crypt, err = NewBlowfishBlockCrypt(pass)
case "twofish":
crypt, err = NewTwofishBlockCrypt(pass)
case "cast5":
crypt, err = NewCast5BlockCrypt(pass[:16])
case "3des":
crypt, err = NewTripleDESBlockCrypt(pass[:24])
case "xtea":
crypt, err = NewXTEABlockCrypt(pass[:16])
case "salsa20":
crypt, err = NewSalsa20BlockCrypt(pass)
case "chacha20":
crypt, err = NewChacha20BlockCrypt(pass)
default:
endeInfo.Crypt = "aes"
crypt, err = NewAESBlockCrypt(pass)
}
if (nil != err) {
return err
}
endeCode = crypt
return nil
}