-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcrypto_helper.go
executable file
·545 lines (490 loc) · 12.5 KB
/
crypto_helper.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
* Description : 加密解码相关封装方法 TODO 测试
* Author : ManGe
* Mail : 2912882908@qq.com
**/
package gathertool
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"errors"
"fmt"
"hash"
"io"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/pbkdf2"
)
const (
CBC = "CBC"
ECB = "ECB"
CFB = "CFB"
CTR = "CTR"
)
// AES AES interface
type AES interface {
Encrypt(str, key []byte) ([]byte, error)
Decrypt(str, key []byte) ([]byte, error)
}
// DES DES interface
type DES interface {
Encrypt(str, key []byte) ([]byte, error)
Decrypt(str, key []byte) ([]byte, error)
}
// NewAES : use NewAES(AES_CBC)
func NewAES(typeName string, arg ...[]byte) AES {
iv := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}
if len(arg) != 0 {
iv = arg[0]
}
switch typeName {
case "cbc", "Cbc", CBC:
return &cbcObj{
cryptoType: "aes",
iv: iv,
}
case "ecb", "Ecb", ECB:
return &ecbObj{
cryptoType: "aes",
}
case "cfb", "Cfb", CFB:
return &cfbObj{
cryptoType: "aes",
}
case "ctr", "Ctr", CTR:
return &ctrObj{
cryptoType: "aes",
count: iv,
}
default:
return &cbcObj{
iv: iv,
}
}
}
// NewDES : use NewDES(DES_CBC)
func NewDES(typeName string, arg ...[]byte) DES {
iv := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}
if len(arg) != 0 {
iv = arg[0]
}
switch typeName {
case "cbc", "Cbc", CBC:
return &cbcObj{
cryptoType: "des",
iv: iv,
}
case "ecb", "Ecb", ECB:
return &ecbObj{
cryptoType: "des",
}
case "cfb", "Cfb", CFB:
return &cfbObj{
cryptoType: "des",
}
case "ctr", "Ctr", CTR:
return &ctrObj{
count: iv,
cryptoType: "des",
}
default:
return &cbcObj{
iv: iv,
cryptoType: "des",
}
}
}
// CBC : 密码分组链接模式(Cipher Block Chaining (CBC)) default
type cbcObj struct {
cryptoType string
iv []byte
}
func (cbc *cbcObj) getBlock(key []byte) (block cipher.Block, err error) {
if cbc.cryptoType == "aes" {
block, err = aes.NewCipher(key)
}
if cbc.cryptoType == "des" {
block, err = des.NewCipher(key)
}
return
}
// Encrypt AES CBC Encrypt
func (cbc *cbcObj) Encrypt(str, key []byte) ([]byte, error) {
block, err := cbc.getBlock(key)
if err != nil {
Error("[" + cbc.cryptoType + "-CBC] ERROR:" + err.Error())
return []byte(""), err
}
blockSize := block.BlockSize()
originData := cbc.pkcs5Padding(str, blockSize)
blockMode := cipher.NewCBCEncrypter(block, cbc.iv)
cryptData := make([]byte, len(originData))
blockMode.CryptBlocks(cryptData, originData)
P2E()
return cryptData, nil
}
// Decrypt AES CBC Decrypt
func (cbc *cbcObj) Decrypt(str, key []byte) ([]byte, error) {
block, err := cbc.getBlock(key)
if err != nil {
Error("[" + cbc.cryptoType + "-CBC] ERROR:" + err.Error())
return []byte(""), err
}
blockMode := cipher.NewCBCDecrypter(block, cbc.iv)
originStr := make([]byte, len(str))
blockMode.CryptBlocks(originStr, str)
P2E()
return cbc.pkcs5UnPadding(originStr), nil
}
func (cbc *cbcObj) pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
func (cbc *cbcObj) pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unPadDing := int(origData[length-1])
return origData[:(length - unPadDing)]
}
// ECB : 电码本模式(Electronic Codebook Book (ECB))
type ecbObj struct {
cryptoType string
}
func (ecb *ecbObj) getBlock(key []byte) (block cipher.Block, err error) {
if ecb.cryptoType == "aes" {
block, err = aes.NewCipher(ecb.generateKey(key))
}
if ecb.cryptoType == "des" {
block, err = des.NewCipher(key)
}
return
}
// Encrypt AES ECB Encrypt
func (ecb *ecbObj) Encrypt(str, key []byte) ([]byte, error) {
block, err := ecb.getBlock(key)
if err != nil {
Error("[" + ecb.cryptoType + "-ECB] ERROR:" + err.Error())
return []byte(""), err
}
blockSize := block.BlockSize()
if ecb.cryptoType == "aes" {
str = ecb.pkcs5PaddingAes(str, blockSize)
}
if ecb.cryptoType == "des" {
str = ecb.pkcs5PaddingDes(str, blockSize)
}
//返回加密结果
encryptData := make([]byte, len(str))
//存储每次加密的数据
tmpData := make([]byte, blockSize)
//分组分块加密
for index := 0; index < len(str); index += blockSize {
block.Encrypt(tmpData, str[index:index+blockSize])
copy(encryptData, tmpData)
}
P2E()
return encryptData, nil
}
func (ecb *ecbObj) pkcs5PaddingDes(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
func (ecb *ecbObj) pkcs5PaddingAes(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
if padding != 0 {
ciphertext = append(ciphertext, bytes.Repeat([]byte{byte(0)}, padding)...)
}
return ciphertext
}
// Decrypt AES ECB Decrypt
func (ecb *ecbObj) Decrypt(str, key []byte) ([]byte, error) {
block, err := ecb.getBlock(key)
if err != nil {
Error("[" + ecb.cryptoType + "-ECB] ERROR:" + err.Error())
return []byte(""), err
}
blockSize := block.BlockSize()
//返回加密结果
decryptData := make([]byte, len(str))
//存储每次加密的数据
tmpData := make([]byte, blockSize)
//分组分块加密
for index := 0; index < len(str); index += blockSize {
block.Decrypt(tmpData, str[index:index+blockSize])
copy(decryptData, tmpData)
}
if ecb.cryptoType == "des" {
return ecb.pkcs5UnPadding(decryptData), nil
}
P2E()
return ecb.unPadding(decryptData), nil
}
func (ecb *ecbObj) generateKey(key []byte) (genKey []byte) {
genKey = make([]byte, 16)
copy(genKey, key)
for i := 16; i < len(key); {
for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
genKey[j] ^= key[i]
}
}
return genKey
}
func (ecb *ecbObj) unPadding(src []byte) []byte {
for i := len(src) - 1; ; i-- {
if src[i] != 0 {
return src[:i+1]
}
}
}
func (ecb *ecbObj) pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}
// 密码反馈模式(Cipher FeedBack (CFB))
type cfbObj struct {
cryptoType string
}
func (cfb *cfbObj) getBlock(key []byte) (block cipher.Block, err error) {
if cfb.cryptoType == "aes" {
block, err = aes.NewCipher(key)
}
if cfb.cryptoType == "des" {
block, err = des.NewCipher(key)
}
return
}
// Encrypt AES CFB Encrypt
func (cfb *cfbObj) Encrypt(str, key []byte) ([]byte, error) {
P2E()
block, err := cfb.getBlock(key)
if err != nil {
Error("[" + cfb.cryptoType + "-CFB] ERROR:" + err.Error())
return nil, err
}
if cfb.cryptoType == "aes" {
encrypted := make([]byte, aes.BlockSize+len(str))
iv := encrypted[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(encrypted[aes.BlockSize:], str)
return encrypted, nil
}
if cfb.cryptoType == "des" {
encrypted := make([]byte, des.BlockSize+len(str))
iv := encrypted[:des.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(encrypted[des.BlockSize:], str)
return encrypted, nil
}
return nil, nil
}
// Decrypt AES CFB Decrypt
func (cfb *cfbObj) Decrypt(str, key []byte) ([]byte, error) {
P2E()
block, err := cfb.getBlock(key)
if err != nil {
Error("[" + cfb.cryptoType + "-CFB] ERROR:" + err.Error())
return nil, err
}
iv := make([]byte, 0)
if cfb.cryptoType == "aes" {
if len(str) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv = str[:aes.BlockSize]
str = str[aes.BlockSize:]
}
if cfb.cryptoType == "des" {
if len(str) < des.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv = str[:des.BlockSize]
str = str[des.BlockSize:]
}
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(str, str)
return str, nil
}
// 计算器模式(Counter (CTR))
type ctrObj struct {
count []byte //指定计数器,长度必须等于block的块尺寸
cryptoType string
}
func (ctr *ctrObj) getBlock(key []byte) (block cipher.Block, err error) {
if ctr.cryptoType == "aes" {
block, err = aes.NewCipher(key)
}
if ctr.cryptoType == "des" {
block, err = des.NewCipher(key)
if len(ctr.count) > des.BlockSize {
ctr.count = ctr.count[0:des.BlockSize]
}
}
return
}
// Encrypt AES CTR Encrypt
func (ctr *ctrObj) Encrypt(str, key []byte) ([]byte, error) {
return ctr.crypto(str, key)
}
// Decrypt AES CTR Decrypt
func (ctr *ctrObj) Decrypt(str, key []byte) ([]byte, error) {
return ctr.crypto(str, key)
}
func (ctr *ctrObj) crypto(str, key []byte) ([]byte, error) {
P2E()
block, err := ctr.getBlock(key)
if err != nil {
Error("[AES-CTR] ERROR:" + err.Error())
return []byte(""), err
}
//指定分组模式
blockMode := cipher.NewCTR(block, ctr.count)
//执行加密、解密操作
res := make([]byte, len(str))
blockMode.XORKeyStream(res, str)
//返回明文或密文
return res, nil
}
// 输出反馈模式(Output FeedBack (OFB))
type ofbObj struct{}
func hmacFunc(h func() hash.Hash, str, key []byte) string {
mac := hmac.New(h, key)
mac.Write(str)
res := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return res
}
// HmacMD5 hmac md5
func HmacMD5(str, key string) string {
return hmacFunc(md5.New, []byte(str), []byte(key))
}
// HmacSHA1 hmac sha1
func HmacSHA1(str, key string) string {
return hmacFunc(sha1.New, []byte(str), []byte(key))
}
// HmacSHA256 hmac sha256
func HmacSHA256(str, key string) string {
return hmacFunc(sha256.New, []byte(str), []byte(key))
}
// HmacSHA512 hmac sha512
func HmacSHA512(str, key string) string {
return hmacFunc(sha512.New, []byte(str), []byte(key))
}
func pbkdf2Func(h func() hash.Hash, str, salt []byte, iterations, keySize int) []byte {
return pbkdf2.Key(str, salt, iterations, keySize, h)
}
func PBKDF2(str, salt []byte, iterations, keySize int) []byte {
return pbkdf2Func(sha256.New, str, salt, iterations, keySize)
}
// jwtEncrypt
func jwtEncrypt(token *jwt.Token, data map[string]any, secret string) (string, error) {
claims := make(jwt.MapClaims)
for k, v := range data {
claims[k] = v
}
token.Claims = claims
return token.SignedString([]byte(secret))
}
// JwtEncrypt jwt Encrypt
func JwtEncrypt(data map[string]any, secret, method string) (string, error) {
switch method {
case "256":
return jwtEncrypt(jwt.New(jwt.SigningMethodHS256), data, secret)
case "384":
return jwtEncrypt(jwt.New(jwt.SigningMethodHS384), data, secret)
case "512":
return jwtEncrypt(jwt.New(jwt.SigningMethodHS512), data, secret)
}
return "", fmt.Errorf("未知method; method= 256 or 384 or 512 ")
}
func JwtEncrypt256(data map[string]any, secret string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
return jwtEncrypt(token, data, secret)
}
func JwtEncrypt384(data map[string]any, secret string) (string, error) {
token := jwt.New(jwt.SigningMethodHS384)
return jwtEncrypt(token, data, secret)
}
func JwtEncrypt512(data map[string]any, secret string) (string, error) {
token := jwt.New(jwt.SigningMethodHS512)
return jwtEncrypt(token, data, secret)
}
// JwtDecrypt jwt decrypt
func JwtDecrypt(tokenString, secret string) (data map[string]any, err error) {
data = make(map[string]any)
var secretFunc = func() jwt.Keyfunc { //按照这样的规则解析
return func(t *jwt.Token) (any, error) {
return []byte(secret), nil
}
}
token, err := jwt.Parse(tokenString, secretFunc())
if err != nil {
err = fmt.Errorf("未知Token")
return
}
claim, ok := token.Claims.(jwt.MapClaims)
if !ok {
return
}
if !token.Valid {
// 令牌错误
return
}
for k, v := range claim {
data[k] = v
}
return
}
/*
0: “sha1”
1: “sha224”
2: “sha256”
3: “sha384”
4: “sha512”
5: “md5”
6: “rmd160”
7: “sha224WithRSAEncryption”
8: “RSA-SHA224”
9: “sha256WithRSAEncryption”
10: “RSA-SHA256”
11: “sha384WithRSAEncryption”
12: “RSA-SHA384”
13: “sha512WithRSAEncryption”
14: “RSA-SHA512”
15: “RSA-SHA1”
16: “ecdsa-with-SHA1”
17: “sha256”
18: “sha224”
19: “sha384”
20: “sha512”
21: “DSA-SHA”
22: “DSA-SHA1”
23: “DSA”
24: “DSA-WITH-SHA224”
25: “DSA-SHA224”
26: “DSA-WITH-SHA256”
27: “DSA-SHA256”
28: “DSA-WITH-SHA384”
29: “DSA-SHA384”
30: “DSA-WITH-SHA512”
31: “DSA-SHA512”
32: “DSA-RIPEMD160”
33: “ripemd160WithRSA”
34: “RSA-RIPEMD160”
35: “md5WithRSAEncryption”
36: “RSA-MD5”
*/