-
Notifications
You must be signed in to change notification settings - Fork 43
/
aes_ecb.go
74 lines (59 loc) · 1.87 KB
/
aes_ecb.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
package codec
import "crypto/aes"
func _AESECBEncryptWithPadding(key []byte, i interface{}, iv []byte, padding func(i []byte) []byte) ([]byte, error) {
data := interfaceToBytes(i)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
data = padding(data)
encrypted := make([]byte, len(data))
size := block.BlockSize()
if iv == nil {
iv = key[:size]
}
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
block.Encrypt(encrypted[bs:be], data[bs:be])
}
return encrypted, nil
}
func AESECBEncrypt(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESECBEncryptWithPadding(key, i, iv, PKCS7Padding)
}
var AESECBEncryptWithPKCS7Padding = AESECBEncrypt
func AESECBEncryptWithZeroPadding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESECBEncryptWithPadding(key, i, iv, func(i []byte) []byte {
return ZeroPadding(i, aes.BlockSize)
})
}
func _AESECBDecryptWithPadding(key []byte, i interface{}, iv []byte, padding func([]byte) []byte) ([]byte, error) {
crypted := interfaceToBytes(i)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
decrypted := make([]byte, len(crypted))
size := block.BlockSize()
if iv == nil {
iv = key[:size]
}
if len(iv) < size {
iv = padding(iv)
} else if len(iv) > size {
iv = iv[:size]
}
for bs, be := 0, size; bs < len(crypted); bs, be = bs+size, be+size {
block.Decrypt(decrypted[bs:be], crypted[bs:be])
}
decrypted = padding(decrypted)
return decrypted, nil
}
func AESECBDecryptWithPKCS7Padding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESECBDecryptWithPadding(key, i, iv, PKCS7UnPadding)
}
var AESECBDecrypt = AESECBDecryptWithPKCS7Padding
func AESECBDecryptWithZeroPadding(key []byte, i interface{}, iv []byte) ([]byte, error) {
return _AESECBDecryptWithPadding(key, i, iv, func(i []byte) []byte {
return ZeroUnPadding(i)
})
}