-
Notifications
You must be signed in to change notification settings - Fork 45
/
aes_cbc.go
77 lines (61 loc) · 1.91 KB
/
aes_cbc.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
package codec
import (
"crypto/aes"
"crypto/cipher"
)
func AESCBCEncryptWithPKCS7Padding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESCBCEncryptWithPadding(key, i, iv, PKCS7Padding)
}
func AESCBCEncryptWithZeroPadding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESCBCEncryptWithPadding(key, i, iv, func(i []byte) []byte {
return ZeroPadding(i, aes.BlockSize)
})
}
var AESCBCEncrypt = AESCBCEncryptWithPKCS7Padding
func _AESCBCEncryptWithPadding(key []byte, i interface{}, iv []byte, padding func([]byte) []byte) (data []byte, _ error) {
origData := interfaceToBytes(i)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if iv == nil {
iv = key[:blockSize]
}
if len(iv) > blockSize {
iv = iv[:blockSize]
}
origData = padding(origData)
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func _AESCBCDecryptWithUnpadding(key []byte, i interface{}, iv []byte, unpadding func([]byte) []byte) ([]byte, error) {
crypted := interfaceToBytes(i)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if iv == nil {
iv = key[:blockSize]
}
if len(iv) > blockSize {
iv = iv[:blockSize]
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = unpadding(origData)
return origData, nil
}
func AESCBCDecryptWithPKCS7Padding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESCBCDecryptWithUnpadding(key, i, iv, PKCS7UnPadding)
}
func AESCBCDecryptWithZeroPadding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESCBCDecryptWithUnpadding(key, i, iv, func(i []byte) []byte {
return ZeroUnPadding(i)
})
}
var AESCBCDecrypt = AESCBCDecryptWithPKCS7Padding