Quellcode durchsuchen

change encrypt message

张延森 vor 3 Jahren
Ursprung
Commit
488d5228f6
1 geänderte Dateien mit 14 neuen und 31 gelöschten Zeilen
  1. 14
    31
      utils/encrypt/msg_encrypt.go

+ 14
- 31
utils/encrypt/msg_encrypt.go Datei anzeigen

@@ -16,41 +16,32 @@ import (
16 16
 	"bytes"
17 17
 	"crypto/aes"
18 18
 	"crypto/cipher"
19
-	"encoding/base64"
20 19
 	"errors"
21 20
 )
22 21
 
23 22
 // MsgEncode 使用 AES CBC 模式加密数据
24 23
 // data 为待加密数据
25
-func MsgEncode(data []byte, encodingAESKey, iv string) ([]byte, error) {
26
-	if encodingAESKey == "" {
27
-		return nil, errors.New("加密 EncodingAESKey 为空")
28
-	}
29
-
30
-	if iv == "" {
31
-		return nil, errors.New("加密 IV 为空")
32
-	}
33
-
24
+func MsgEncode(data, key []byte) ([]byte, error) {
34 25
 	if nil == data || len(data) == 0 {
35 26
 		return nil, errors.New("待加密 消息 为空")
36 27
 	}
37 28
 
38
-	aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
39
-	if e1 != nil {
40
-		return nil, e1
29
+	if nil == key || len(key) == 0 {
30
+		return nil, errors.New("加密 AESKey 为空")
41 31
 	}
42 32
 
43
-	block, e2 := aes.NewCipher(aesKey)
33
+	block, e2 := aes.NewCipher(key)
44 34
 	if e2 != nil {
45 35
 		return nil, e2
46 36
 	}
47 37
 
48 38
 	blockSize := block.BlockSize()
49
-	dist := pkcs7(data, blockSize)
39
+	cipherData := pkcs7(data, blockSize)
40
+	dist := make([]byte, len(cipherData))
50 41
 
51 42
 	// CBC
52
-	mode := cipher.NewCBCEncrypter(block, []byte(iv))
53
-	mode.CryptBlocks(dist, data)
43
+	mode := cipher.NewCBCEncrypter(block, key[:blockSize])
44
+	mode.CryptBlocks(dist, cipherData)
54 45
 
55 46
 	// 如果需要拿到字符串, 请使用
56 47
 	// fmt.Sprintf("%x", xxx)
@@ -60,32 +51,24 @@ func MsgEncode(data []byte, encodingAESKey, iv string) ([]byte, error) {
60 51
 
61 52
 // MsgDecode 是 MsgEncode 的反操作, 用来解密数据
62 53
 // data 为待解密数据
63
-func MsgDecode(data []byte, encodingAESKey, iv string) ([]byte, error) {
64
-	if encodingAESKey == "" {
65
-		return nil, errors.New("解密 EncodingAESKey 为空")
66
-	}
67
-
68
-	if iv == "" {
69
-		return nil, errors.New("解密 IV 为空")
70
-	}
71
-
54
+func MsgDecode(data, key []byte) ([]byte, error) {
72 55
 	if nil == data || len(data) == 0 {
73 56
 		return nil, errors.New("待解密 消息 为空")
74 57
 	}
75 58
 
76
-	aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
77
-	if e1 != nil {
78
-		return nil, e1
59
+	if nil == key || len(key) == 0 {
60
+		return nil, errors.New("解密 AESKey 为空")
79 61
 	}
80 62
 
81
-	block, err := aes.NewCipher(aesKey)
63
+	block, err := aes.NewCipher(key)
82 64
 	if err != nil {
83 65
 		return nil, err
84 66
 	}
85 67
 
68
+	blockSize := block.BlockSize()
86 69
 	dist := make([]byte, len(data))
87 70
 
88
-	mode := cipher.NewCBCDecrypter(block, []byte(iv))
71
+	mode := cipher.NewCBCDecrypter(block, key[:blockSize])
89 72
 	mode.CryptBlocks(dist, data)
90 73
 
91 74
 	// 如果需要拿到字符串, 请使用