-
Notifications
You must be signed in to change notification settings - Fork 4
/
aes.go
61 lines (55 loc) · 1.41 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
package Figo
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
//AES/CBC/PKCS5Padding
type AesHelp struct {
key []byte
iv []byte
}
func NewAesHelp(keyParam []byte, ivParam ...byte) AesHelp {
key, iv := keyParam, keyParam
if len(ivParam) > 0 {
iv = ivParam
}
return AesHelp{
key: key,
iv: iv,
}
}
func (p *AesHelp) Encrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher(p.key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
PKCS5Padding := func(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, p.iv[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func (p *AesHelp) Decrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher(p.key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, p.iv[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
PKCS5UnPadding := func(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
origData = PKCS5UnPadding(origData)
return origData, nil
}