/
cipher.go
94 lines (78 loc) · 1.85 KB
/
cipher.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
package tool
import (
"crypto/aes"
"crypto/des"
"crypto/cipher"
"golang.org/x/crypto/tea"
"golang.org/x/crypto/xtea"
"golang.org/x/crypto/cast5"
"golang.org/x/crypto/twofish"
"golang.org/x/crypto/blowfish"
"github.com/deatil/go-cryptobin/cipher/sm4"
)
type (
// CipherFunc
CipherFunc = func([]byte) (cipher.Block, error)
// CipherFunc map 列表
CipherFuncMap = map[string]CipherFunc
)
var (
newXteaCipher = func(key []byte) (cipher.Block, error) {
return xtea.NewCipher(key)
}
newTwofishCipher = func(key []byte) (cipher.Block, error) {
return twofish.NewCipher(key)
}
newBlowfishCipher = func(key []byte) (cipher.Block, error) {
return blowfish.NewCipher(key)
}
newCast5Cipher = func(key []byte) (cipher.Block, error) {
return cast5.NewCipher(key)
}
)
// 默认列表
var defaultCipherFuncs = CipherFuncMap{
"Aes": aes.NewCipher,
"Des": des.NewCipher,
"TripleDes": des.NewTripleDESCipher,
"Tea": tea.NewCipher,
"Xtea": newXteaCipher,
"Twofish": newTwofishCipher,
"Blowfish": newBlowfishCipher,
"Cast5": newCast5Cipher,
"SM4": sm4.NewCipher,
}
/**
* 加密方式
*
* @create 2022-7-26
* @author deatil
*/
type Cipher struct {
// 列表
funcs CipherFuncMap
}
// 构造函数
func NewCipher() Cipher {
cipher := Cipher{
funcs: defaultCipherFuncs,
}
return cipher
}
// 覆盖
func (this Cipher) WithFunc(funcs CipherFuncMap) Cipher {
this.funcs = funcs
return this
}
// 添加
func (this Cipher) AddFunc(name string, block CipherFunc) Cipher {
this.funcs[name] = block
return this
}
// 类型
func (this Cipher) GetFunc(name string) CipherFunc {
if fn, ok := this.funcs[name]; ok {
return fn
}
return this.funcs["Aes"]
}