-
-
Notifications
You must be signed in to change notification settings - Fork 525
/
basic_encryption.go
60 lines (48 loc) · 1.45 KB
/
basic_encryption.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
package requests
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
)
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5Trimming(encrypt []byte) []byte {
padding := encrypt[len(encrypt)-1]
return encrypt[:len(encrypt)-int(padding)]
}
func Decrypt(cipherText, hexKey, hexIV string) string {
if len(cipherText) == 0 || len(hexKey) == 0 || len(hexIV) == 0 {
return ""
}
secretKey, _ := hex.DecodeString(hexKey)
ivParameter, _ := hex.DecodeString(hexIV)
block, err := aes.NewCipher(secretKey)
if err != nil {
return ""
}
decrypter := cipher.NewCBCDecrypter(block, ivParameter)
text, _ := hex.DecodeString(cipherText)
decrypted := make([]byte, len(text))
decrypter.CryptBlocks(decrypted, text)
return string(PKCS5Trimming(decrypted))
}
func Encrypt(plainText, hexKey, hexIV string) string {
if len(plainText) == 0 || len(hexKey) == 0 || len(hexIV) == 0 {
return ""
}
secretKey, _ := hex.DecodeString(hexKey)
ivParameter, _ := hex.DecodeString(hexIV)
block, err := aes.NewCipher(secretKey)
if err != nil {
return ""
}
content := PKCS5Padding([]byte(plainText), block.BlockSize())
encrypter := cipher.NewCBCEncrypter(block, ivParameter)
ciphertext := make([]byte, len(content))
encrypter.CryptBlocks(ciphertext, content)
return hex.EncodeToString(ciphertext)
}