-
Notifications
You must be signed in to change notification settings - Fork 21
/
cipher.go
143 lines (111 loc) · 2.81 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
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
package pbes2
import(
"io"
"fmt"
"sync"
"encoding/asn1"
"crypto/x509/pkix"
"github.com/deatil/go-cryptobin/tool"
)
// 加密接口
type Cipher interface {
// oid
OID() asn1.ObjectIdentifier
// 值大小
KeySize() int
// 是否有 KeyLength
HasKeyLength() bool
// 密码是否需要 Bmp 处理
NeedBmpPassword() bool
// 加密, 返回: [加密后数据, 参数, error]
Encrypt(rand io.Reader, key, plaintext []byte) ([]byte, []byte, error)
// 解密
Decrypt(key, params, ciphertext []byte) ([]byte, error)
}
// ===============
// 默认
var defaultCiphers = NewCiphers()
// 方法
type CipherFunc = func() Cipher
// Ciphers
type Ciphers struct {
// 读写锁
mu sync.RWMutex
// 列表
ciphers map[string]CipherFunc
}
func NewCiphers() *Ciphers {
return &Ciphers {
ciphers: make(map[string]CipherFunc),
}
}
// 添加加密
func (this *Ciphers) AddCipher(oid asn1.ObjectIdentifier, cipher CipherFunc) {
this.mu.Lock()
defer this.mu.Unlock()
this.ciphers[oid.String()] = cipher
}
// 添加加密
func AddCipher(oid asn1.ObjectIdentifier, cipher CipherFunc) {
defaultCiphers.AddCipher(oid, cipher)
}
// 获取加密
func (this *Ciphers) GetCipher(alg any) (Cipher, error) {
this.mu.RLock()
defer this.mu.RUnlock()
var oid string
switch scheme := alg.(type) {
case string:
oid = scheme
case pkix.AlgorithmIdentifier:
oid = scheme.Algorithm.String()
// 国密加密判断
if oid == oidSM4.String() {
if len(scheme.Parameters.Bytes) != 0 ||
len(scheme.Parameters.FullBytes) != 0 {
oid = oidSM4CBC.String()
} else {
oid = oidSM4ECB.String()
}
}
}
newCipher, ok := this.ciphers[oid]
if !ok {
return nil, fmt.Errorf("pkcs/cipher: unsupported cipher (OID: %s)", oid)
}
return newCipher(), nil
}
// 获取加密
func GetCipher(alg any) (Cipher, error) {
return defaultCiphers.GetCipher(alg)
}
// 全部
func (this *Ciphers) All() map[string]CipherFunc {
this.mu.RLock()
defer this.mu.RUnlock()
return this.ciphers
}
// 全部
func AllCipher() map[string]CipherFunc {
return defaultCiphers.All()
}
// 克隆
func (this *Ciphers) Clone() *Ciphers {
return &Ciphers {
ciphers: this.ciphers,
}
}
// 克隆
func CloneCiphers() *Ciphers {
return defaultCiphers.Clone()
}
// ===============
var newPadding = tool.NewPadding()
// 明文补码算法
func pkcs7Padding(text []byte, blockSize int) []byte {
return newPadding.PKCS7Padding(text, blockSize)
}
// 明文减码算法
func pkcs7UnPadding(src []byte) ([]byte, error) {
return newPadding.PKCS7UnPadding(src)
}