-
Notifications
You must be signed in to change notification settings - Fork 9
/
aes.go
35 lines (32 loc) · 933 Bytes
/
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
package encrypt
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
// AesEncrypt deifned
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = pkcs5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key)
encrypted := make([]byte, len(origData))
blockMode.CryptBlocks(encrypted, origData)
return []byte(base64.URLEncoding.EncodeToString(encrypted)), nil
}
// AesDecrypt defined
func AesDecrypt(crypted, key []byte) ([]byte, error) {
decryptBytes, err := base64.URLEncoding.DecodeString(string(crypted))
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, key)
decrypted := make([]byte, len(decryptBytes))
blockMode.CryptBlocks(decrypted, crypted)
decrypted = pkcs5UnPadding(decrypted)
return decrypted, nil
}