-
Notifications
You must be signed in to change notification settings - Fork 9
/
encryption.go
executable file
·103 lines (87 loc) · 1.83 KB
/
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
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
97
98
99
100
101
102
103
package toolkit
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
)
func MD5String(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
func GenerateRandomString(baseChars string, n int) string {
if baseChars == "" {
baseChars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz@#!"
}
baseCharsLen := len(baseChars)
rnd := ""
for i := 0; i < n; i++ {
x := RandInt(baseCharsLen)
rnd += string(baseChars[x])
}
return rnd
}
func FileChecksum(fileLocation string) string {
f, err := os.Open(fileLocation)
if f != nil {
defer f.Close()
}
if err != nil {
return ""
}
hash := md5.New()
_, err = io.Copy(hash, f)
if err != nil {
return ""
}
hashed := hash.Sum(nil)
return fmt.Sprintf("%x", hashed)
}
func EncryptAES(text, key string) (string, error) {
plaintext := []byte(text)
c, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
result := fmt.Sprintf("%x", ciphertext)
return result, nil
}
func DecryptAES(text, key string) (string, error) {
ciphertext, err := hex.DecodeString(text)
if err != nil {
return "", err
}
c, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return "", err
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
res, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
result := fmt.Sprintf("%s", res)
return result, nil
}