-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
48 lines (39 loc) · 1.17 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
package mklic
import (
"bytes"
"crypto/aes"
"encoding/base64"
)
func aesEncrypt(in []byte, key string) string {
block, _ := aes.NewCipher([]byte(key))
in = pKCS7Padding(in, block.BlockSize())
encrypted := make([]byte, len(in))
size := block.BlockSize()
for bs, be := 0, size; bs < len(in); bs, be = bs+size, be+size {
block.Encrypt(encrypted[bs:be], in[bs:be])
}
return base64.StdEncoding.EncodeToString(encrypted)
}
func aesDecrypt(in []byte, key string) ([]byte, error) {
content, err := base64.StdEncoding.DecodeString(string(in))
if err != nil {
return nil, err
}
block, _ := aes.NewCipher([]byte(key))
decrypted := make([]byte, len(content))
size := block.BlockSize()
for bs, be := 0, size; bs < len(content); bs, be = bs+size, be+size {
block.Decrypt(decrypted[bs:be], content[bs:be])
}
return pKCS7UnPadding(decrypted), nil
}
func pKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func pKCS7UnPadding(s []byte) []byte {
length := len(s)
padding := int(s[length-1])
return s[:(length - padding)]
}