fastEndecode2.go
2.6 KB
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
package fastEncryptDecode
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/hex"
"strconv"
"strings"
)
//md5 相关
//string to md5
func MD5hash(code []byte) string {
h := md5.New()
h.Write(code)
rs := hex.EncodeToString(h.Sum(nil))
return rs
}
//md5校验
func MD5Verify(code string, md5Str string) bool {
codeMD5 := MD5hash([]byte(code))
return 0 == strings.Compare(codeMD5, md5Str)
}
type KeySizeError int
func (k KeySizeError) Error() string {
return "fastEncryptDecode/fastEnDeCode: invalid key size " + strconv.Itoa(int(k)) + " | key size must be 16"
}
func checkKeySize(key []byte) error {
len := len(key)
if len != 16 {
return KeySizeError(len)
}
return nil
}
// AES encrypt pkcs7padding CBC, key for choose algorithm
func AES_CBC_PKCS7_EncryptByte(plantText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
plantText = pKCS7Padding(plantText, block.BlockSize())
//偏转向量iv长度等于密钥key的长度
iv := key[:block.BlockSize()]
blockModel := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte, len(plantText))
blockModel.CryptBlocks(cipherText, plantText)
return cipherText, nil
}
func AES_CBC_PKCS7_DecryptByte(cipherText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
keyBytes := []byte(key)
block, err := aes.NewCipher(keyBytes)
if err != nil {
return nil, err
}
//偏转向量iv长度等于密钥key的长度
iv := key[:block.BlockSize()]
blockModel := cipher.NewCBCDecrypter(block, iv)
plantText := make([]byte, len(cipherText))
blockModel.CryptBlocks(plantText, cipherText)
plantText = pKCS7UnPadding(plantText, block.BlockSize())
return plantText, nil
}
//AES Decrypt pkcs7padding CBC, key for choose algorithm
func pKCS7UnPadding(plantText []byte, blockSize int) []byte {
length := len(plantText)
unPadding := int(plantText[length-1])
return plantText[:(length - unPadding)]
}
func pKCS7Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
// func PKCS5Padding(cipherText []byte, blockSize int) []byte {
// padding := blockSize - len(cipherText)%blockSize
// padText := bytes.Repeat([]byte{byte(padding)}, padding)
// return append(cipherText, padText...)
// }
// func PKCS5UnPadding(origData []byte) []byte {
// length := len(origData)
// // 去掉最后一个字节 unpadding 次
// unpadding := int(origData[length-1])
// return origData[:(length - unpadding)]
// }