-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathaes.go
More file actions
57 lines (50 loc) · 1.33 KB
/
aes.go
File metadata and controls
57 lines (50 loc) · 1.33 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
package hltool
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
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)]
}
// GoAES 加密
type GoAES struct {
Key []byte
}
// NewGoAES 返回GoAES
func NewGoAES(key []byte) *GoAES {
return &GoAES{Key: key}
}
// Encrypt 加密数据
func (a *GoAES) Encrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher(a.Key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = pKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, a.Key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// Decrypt 解密数据
func (a *GoAES) Decrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher(a.Key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, a.Key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = pKCS7UnPadding(origData)
return origData, nil
}