-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEncrypt.go
53 lines (45 loc) · 1.24 KB
/
Encrypt.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
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
func EncryptAES(key []byte, plaintext string) string {
origData := []byte(plaintext)
c, err := aes.NewCipher(key)
CheckError(err)
blockSize := c.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(c, key[:blockSize])
out := make([]byte, len(origData))
blockMode.CryptBlocks(out, origData)
return base64.StdEncoding.EncodeToString(out)
}
func DecryptAES(key []byte, ct string) string {
cipherByte, _ := base64.StdEncoding.DecodeString(ct)
c, err := aes.NewCipher(key)
CheckError(err)
blockSize := c.BlockSize()
blockMode := cipher.NewCBCDecrypter(c, key[:blockSize])
pt := make([]byte, len(cipherByte))
blockMode.CryptBlocks(pt, cipherByte)
pt = PKCS7UnPadding(pt)
s := string(pt[:])
return s
}
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(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func CheckError(err error) {
if err != nil {
panic(err)
}
}