forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.go
96 lines (78 loc) · 2.04 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
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
90
91
92
93
94
95
96
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
crand "crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"io"
)
func Sha2Encrypt(raw string) string {
// return 64-bit hash
hash := sha256.Sum256([]byte(raw))
return hex.EncodeToString(hash[:])
}
func Sha2EncryptForm(form interface{}) string {
// return 64-bit hash
hash := sha256.Sum256([]byte(ToJson(form)))
return hex.EncodeToString(hash[:])
}
func Base64Encode(raw string) string {
return base64.StdEncoding.EncodeToString([]byte(raw))
}
func Base64EncodeBytes(raw []byte) string {
return base64.StdEncoding.EncodeToString(raw)
}
func Base64Decode(raw string) ([]byte, error) {
return base64.StdEncoding.DecodeString(raw)
}
func Base64DecodeBytes(raw string) []byte {
if data, err := base64.StdEncoding.DecodeString(raw); err == nil {
return data
} else {
return []byte{}
}
}
func Md5Encrypt(raw string) string {
// return 32-bit hash
hash := md5.Sum([]byte(raw))
return hex.EncodeToString(hash[:])
}
func Md5EncryptForm(form interface{}) string {
// return 32-bit hash
hash := md5.Sum([]byte(ToJson(form)))
return hex.EncodeToString(hash[:])
}
func AES256Encrypt(key string, data string) (string, error) {
text := []byte(data)
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(crand.Reader, iv); err != nil {
return "", err
}
encryptor := cipher.NewCFBEncrypter(block, iv)
ciphertext := make([]byte, len(text))
encryptor.XORKeyStream(ciphertext, text)
return hex.EncodeToString(ciphertext), nil
}
func AES256Decrypt(key string, data string) (string, error) {
ciphertext, err := hex.DecodeString(data)
if err != nil {
return "", err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
decryptor := cipher.NewCFBDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
decryptor.XORKeyStream(plaintext, ciphertext)
return string(plaintext), nil
}