-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes.go
73 lines (65 loc) · 1.53 KB
/
aes.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
package endecrypt
import (
AES "crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func AesConfig(Passphrase string) Aes {
return &aes{
Passphrase: Passphrase,
}
}
type aes struct {
Passphrase string
}
type Aes interface {
Encrypt(plainText string) string
Decrypt(cipherText string) string
}
func GenerateAesKey() string {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
panic(err.Error())
}
return hex.EncodeToString(bytes)
}
func (a *aes) Encrypt(stringToEncrypt string) (encryptedString string) {
key, _ := hex.DecodeString(a.Passphrase)
plaintext := []byte(stringToEncrypt)
block, err := AES.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
return fmt.Sprintf("%x", ciphertext)
}
func (a *aes) Decrypt(encryptedString string) (decryptedString string) {
key, _ := hex.DecodeString(a.Passphrase)
enc, _ := hex.DecodeString(encryptedString)
block, err := AES.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := aesGCM.NonceSize()
nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return fmt.Sprintf("%s", plaintext)
}