-
Notifications
You must be signed in to change notification settings - Fork 0
/
endecrypt.go
89 lines (73 loc) · 2.05 KB
/
endecrypt.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package endecrypt
import (
"bytes"
AES "crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/base64"
"fmt"
)
func EndecryptConfig(SecretKey string, SecretIV string) EncryptDecrypt {
return &endecrypt{
SecretKey: SecretKey,
SecretIV: SecretIV,
}
}
type endecrypt struct {
SecretKey string
SecretIV string
}
type EncryptDecrypt interface {
Encrypt(plainText string) string
Decrypt(cipherText string) string
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
func (a *endecrypt) Encrypt(plainText string) string {
key := fmt.Sprintf("%x", sha256.Sum256([]byte(a.SecretKey)))
key = key[:32]
iv := fmt.Sprintf("%x", sha256.Sum256([]byte(a.SecretIV)))
iv = iv[0:16]
block, err := AES.NewCipher([]byte(key))
if err != nil {
panic(err)
}
ecb := cipher.NewCBCEncrypter(block, []byte(iv))
content := []byte(plainText)
content = PKCS5Padding(content, 16)
if len(content)%AES.BlockSize != 0 {
panic("plaintext is not a multiple of the block size")
}
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
encryptText := base64.StdEncoding.EncodeToString(crypted)
return base64.StdEncoding.EncodeToString([]byte(encryptText))
}
func (a *endecrypt) Decrypt(cipherText string) string {
key := fmt.Sprintf("%x", sha256.Sum256([]byte(a.SecretKey)))
key = key[:32]
iv := fmt.Sprintf("%x", sha256.Sum256([]byte(a.SecretIV)))
iv = iv[0:16]
block, err := AES.NewCipher([]byte(key))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(cipherText)
data, err = base64.StdEncoding.DecodeString(string(data))
if err != nil {
panic(err)
}
ecb := cipher.NewCBCDecrypter(block, []byte(iv))
origData := make([]byte, len(data))
ecb.CryptBlocks(origData, data)
origData = PKCS5UnPadding(origData)
return string(origData)
}