-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes.go
271 lines (252 loc) · 8.34 KB
/
aes.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"io"
)
const (
gcmTagSize = 16 // crypto/cipher.gcmTagSize
gcmStandardNonceSize = 12 // crypto/cipher.gcmStandardNonceSize
)
// GCMEncrypt encrypts plaintext with key using the GCM mode.
// The returned ciphertext contains the nonce, encrypted text and
// the additional data authentication tag. If additional data is not
// provided (as an Option), random data will be generated and used.
//
// GCM模式是CTR和GHASH的组合,GHASH操作定义为密文结果与密钥以及消息长度在GF(2^128)域上相乘。
// GCM比CCM的优势是在于更高并行度及更好的性能。
// TLS1.2标准使用的就是AES-GCM算法,并且Intel CPU提供了GHASH的硬件加速功能。
func GCMEncrypt(plaintext, key []byte, opts ...Option) (ciphertext []byte, err error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
nonceSize := defaultInt(opt.nonceSize, gcmStandardNonceSize)
nonce := make([]byte, nonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCMWithNonceSize(block, nonceSize)
if err != nil {
return nil, err
}
ciphertext = gcm.Seal(nil, nonce, plaintext, opt.additionalData)
ciphertext = append(nonce, ciphertext...) //nolint:makezero
ciphertext, err = opt.encode(ciphertext)
if err != nil {
return nil, err
}
return ciphertext, nil
}
// GCMEncryptNewKey creates a new key and encrypts plaintext with the
// new key using GCM mode.
// The returned ciphertext contains the nonce, encrypted text and
// the additional data authentication tag. If additional data is not
// provided (as an Option), random data will be generated and used.
func GCMEncryptNewKey(plaintext []byte, opts ...Option) (
ciphertext, key, additional []byte, err error,
) {
opt := (&options{}).apply(opts...)
keySize := defaultInt(opt.keySize, 2*aes.BlockSize)
nonceSize := defaultInt(opt.nonceSize, gcmStandardNonceSize)
additional = opt.additionalData
buflen := keySize + nonceSize
if len(additional) == 0 {
buflen += aes.BlockSize
}
buf := make([]byte, buflen)
if _, err = io.ReadFull(rand.Reader, buf); err != nil {
return nil, nil, nil, err
}
nonceEnd := keySize + nonceSize
key = buf[:keySize:keySize]
nonce := buf[keySize:nonceEnd:nonceEnd]
if len(additional) == 0 {
additional = buf[keySize+nonceSize:]
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, nil, err
}
gcm, err := cipher.NewGCMWithNonceSize(block, nonceSize)
if err != nil {
return nil, nil, nil, err
}
ciphertext = gcm.Seal(nil, nonce, plaintext, additional)
ciphertext = append(nonce, ciphertext...)
ciphertext, err = opt.encode(ciphertext)
if err != nil {
return nil, nil, nil, err
}
return ciphertext, key, additional, nil
}
// UnpackGCMCipherText unpacks cipher text returned by GCMEncrypt and
// GCMEncryptNewKey into encrypted text, nonce and authentication tag.
func UnpackGCMCipherText(ciphertext []byte, opts ...Option) (text, nonce, tag []byte) {
opt := (&options{}).apply(opts...)
nonceSize := defaultInt(opt.nonceSize, gcmStandardNonceSize)
tagOffset := len(ciphertext) - gcmTagSize
nonce = ciphertext[:nonceSize:nonceSize]
text = ciphertext[nonceSize:tagOffset:tagOffset]
tag = ciphertext[tagOffset:]
return
}
// GCMDecrypt decrypts ciphertext returned by GCMEncrypt and GCMEncryptNewKey
// into plain text.
func GCMDecrypt(ciphertext, key []byte, opts ...Option) (plaintext []byte, err error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
nonceSize := defaultInt(opt.nonceSize, gcmStandardNonceSize)
ciphertext, err = opt.decode(ciphertext)
if err != nil {
return nil, err
}
nonce := ciphertext[:nonceSize]
ciphertext = ciphertext[nonceSize:]
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCMWithNonceSize(block, nonceSize)
if err != nil {
return nil, err
}
return gcm.Open(nil, nonce, ciphertext, opt.additionalData)
}
// CBCEncrypt encrypts plaintext with key using the CBC mode.
// The given plaintext will be padded following the PKCS#5 standard.
// The returned ciphertext contains the nonce and encrypted data.
//
// CBC - 密码分组链接模式,明文数据需要按分组大小对齐。
func CBCEncrypt(plaintext, key []byte, opts ...Option) (ciphertext []byte, err error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = PKCS5Padding(plaintext, blockSize)
buf := make([]byte, blockSize+len(plaintext))
nonce := buf[:blockSize]
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
encrypter := cipher.NewCBCEncrypter(block, nonce)
encrypter.CryptBlocks(buf[len(nonce):], plaintext)
ciphertext, err = opt.encode(buf)
if err != nil {
return nil, err
}
return ciphertext, nil
}
// CBCDecrypt decrypts ciphertext returned by CBCEncrypt into plain text.
func CBCDecrypt(ciphertext, key []byte, opts ...Option) (plaintext []byte, err error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
ciphertext, err = opt.decode(ciphertext)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
nonce := ciphertext[:blockSize]
ciphertext = ciphertext[blockSize:]
decrypter := cipher.NewCBCDecrypter(block, nonce)
plaintext = make([]byte, len(ciphertext))
decrypter.CryptBlocks(plaintext, ciphertext)
plaintext = PKCS5UnPadding(plaintext)
return plaintext, nil
}
// CFBEncrypt encrypts plaintext with key using the CFB mode.
// The returned cipher text contains the nonce and encrypted data.
//
// CFB - 密文反馈模式,明文数据不需要按分组大小对齐。
func CFBEncrypt(plaintext, key []byte, opts ...Option) ([]byte, error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
buf := make([]byte, blockSize+len(plaintext))
nonce := buf[:blockSize]
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
encrypter := cipher.NewCFBEncrypter(block, nonce)
encrypter.XORKeyStream(buf[len(nonce):], plaintext)
ciphertext, err := opt.encode(buf)
if err != nil {
return nil, err
}
return ciphertext, nil
}
// CFBDecrypt decrypts ciphertext returned by CFBEncrypt.
func CFBDecrypt(ciphertext, key []byte, opts ...Option) ([]byte, error) {
opt := (&options{}).apply(opts...)
key = KeyPadding(key)
ciphertext, err := opt.decode(ciphertext)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
nonce := ciphertext[:blockSize]
ciphertext = ciphertext[blockSize:]
decrypter := cipher.NewCFBDecrypter(block, nonce)
plaintext := make([]byte, len(ciphertext))
decrypter.XORKeyStream(plaintext, ciphertext)
return plaintext, nil
}
// KeyPadding ensures a key's length is either 32, 24 or 16.
// It key's length is greater than 32, it returns the first 32 bytes of key.
// If key's length is not 32, 24 or 16, it appends additional data to key
// using sha256.Sum(key) to make it satisfies the minimal requirement.
func KeyPadding(key []byte) []byte {
length := len(key)
if length == 32 || length == 24 || length == 16 {
return key
}
hash := sha256.Sum256(key)
switch {
case length > 32:
return key[:32]
case length > 24:
return append(key[:length:length], hash[:32-length]...)
case length > 16:
return append(key[:length:length], hash[:24-length]...)
default:
return append(key[:length:length], hash[:16-length]...)
}
}
// PKCS5Padding appends padding data to plaintext following the PKCS#5 standard.
func PKCS5Padding(plaintext []byte, blockSize int) []byte {
padding := blockSize - len(plaintext)%blockSize // 需要padding的数目
padText := bytes.Repeat([]byte{byte(padding)}, padding) // 生成填充文本
return append(plaintext, padText...)
}
// PKCS5UnPadding removes padding data from paddedText following the PKCS#5 standard.
func PKCS5UnPadding(paddedText []byte) []byte {
length := len(paddedText)
unPadding := int(paddedText[length-1])
return paddedText[:(length - unPadding)]
}
func defaultInt(x, defaultValue int) int {
if x == 0 {
return defaultValue
}
return x
}