-
Notifications
You must be signed in to change notification settings - Fork 48
/
aes.go
executable file
·73 lines (62 loc) · 1.45 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
package openssl
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
// AesECBEncrypt
func AesECBEncrypt(src, key []byte, padding string) ([]byte, error) {
block, err := AesNewCipher(key)
if err != nil {
return nil, err
}
return ECBEncrypt(block, src, padding)
}
// AesECBDecrypt
func AesECBDecrypt(src, key []byte, padding string) ([]byte, error) {
block, err := AesNewCipher(key)
if err != nil {
return nil, err
}
return ECBDecrypt(block, src, padding)
}
// AesCBCEncrypt
func AesCBCEncrypt(src, key, iv []byte, padding string) ([]byte, error) {
block, err := AesNewCipher(key)
if err != nil {
return nil, err
}
return CBCEncrypt(block, src, iv, padding)
}
// AesCBCDecrypt
func AesCBCDecrypt(src, key, iv []byte, padding string) ([]byte, error) {
block, err := AesNewCipher(key)
if err != nil {
return nil, err
}
return CBCDecrypt(block, src, iv, padding)
}
// AesNewCipher creates and returns a new AES cipher.Block.
// it will automatically pad the length of the key.
func AesNewCipher(key []byte) (cipher.Block, error) {
return aes.NewCipher(aesKeyPending(key))
}
// aesKeyPending The length of the key can be 16/24/32 characters (128/192/256 bits)
func aesKeyPending(key []byte) []byte {
k := len(key)
count := 0
switch true {
case k <= 16:
count = 16 - k
case k <= 24:
count = 24 - k
case k <= 32:
count = 32 - k
default:
return key[:32]
}
if count == 0 {
return key
}
return append(key, bytes.Repeat([]byte{0}, count)...)
}