forked from AmarnathCJD/gogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes_common.go
46 lines (41 loc) · 1.14 KB
/
aes_common.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
package ige
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
func EncryptAES(data []byte, key string) ([]byte, error) {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
b := pkcs5Padding(data, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, []byte(key)[:block.BlockSize()])
crypted := make([]byte, len(b))
blockMode.CryptBlocks(crypted, b)
return crypted, nil
}
func DecryptAES(data []byte, key string) ([]byte, error) {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(key)[:block.BlockSize()])
origData := make([]byte, len(data))
blockMode.CryptBlocks(origData, data)
origData = pkcs5UnPadding(origData)
return origData, nil
}
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)
if length == 0 {
return origData
}
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}