-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
85 lines (69 loc) · 1.8 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package icrypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"errors"
"fmt"
)
func AESEncryptCBC(key, iv []byte, origData []byte) (encrypted []byte, err error) {
if len(iv) < 16 {
return nil, fmt.Errorf("iv length must lte 16")
}
defer func() {
e := recover()
if e != nil {
err = fmt.Errorf("EncryptCBC %v", e)
}
}()
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
iv = iv[:blockSize]
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
encrypted = make([]byte, len(origData))
blockMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
func AESDecryptCBC(key, iv, encrypted []byte) (origData []byte, err error) {
if len(iv) < 16 {
return nil, fmt.Errorf("iv length must lte 16")
}
defer func() {
e := recover()
if e != nil {
err = fmt.Errorf("DecryptCBC %v", e)
}
}()
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
iv = iv[:blockSize]
blockMode := cipher.NewCBCDecrypter(block, iv)
origData = make([]byte, len(encrypted))
blockMode.CryptBlocks(origData, encrypted)
origData, err = UnPadding(origData)
return origData, err
}
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
func UnPadding(origData []byte) ([]byte, error) {
if len(origData) == 0 {
return origData, nil
}
length := len(origData)
// reduce last byte unPadding
unPadding := int(origData[length-1])
if len(origData) >= (length-unPadding) && (length-unPadding) >= 0 {
return origData[:(length - unPadding)], nil
}
return origData, errors.New("UnPadding error, please check key")
}