-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes.go
66 lines (58 loc) · 1.52 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
package common
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"encoding/hex"
)
func EncryptKey(key []byte, b ...byte) []byte {
h := md5.New()
h.Write(key)
r := md5.New()
p := hex.EncodeToString(h.Sum(b))
r.Write([]byte(p[12:32]))
return []byte(hex.EncodeToString(r.Sum(b)))
}
func AesEncrypt(data, key []byte) (result string, err error) {
key = EncryptKey(key)
block, err := aes.NewCipher(key)
if err != nil {
return
}
blockSize := block.BlockSize()
data = PKCS7Padding(data, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(data))
blockMode.CryptBlocks(crypted, data)
result = base64.StdEncoding.EncodeToString(crypted)
return
}
func AesDecrypt(data string, key []byte) (result []byte, err error) {
result, err = base64.StdEncoding.DecodeString(data)
if err != nil {
return
}
key = EncryptKey(key)
block, err := aes.NewCipher(key)
if err != nil {
return
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(result))
blockMode.CryptBlocks(origData, result)
result = PKCS7UnPadding(origData)
return
}
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}