-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
59 lines (48 loc) · 1 KB
/
crypto.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
package auth
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
type Crypto struct {
Secret []byte
}
func NewCrypto(secret string) *Crypto {
return &Crypto{
Secret: []byte(secret),
}
}
func (cry *Crypto) Encrypt(plainText string) string {
aes, err := aes.NewCipher(cry.Secret)
if err != nil {
panic(err)
}
gcm, _ := cipher.NewGCM(aes)
// if err != nil {
// panic(err)
// }
nonce := make([]byte, gcm.NonceSize())
_, err = rand.Read(nonce)
if err != nil {
panic(err)
}
cipherText := gcm.Seal(nonce, nonce, []byte(plainText), nil)
return string(cipherText)
}
func (cry *Crypto) Decrypt(cipherText string) string {
aes, err := aes.NewCipher(cry.Secret)
if err != nil {
panic(err)
}
gcm, _ := cipher.NewGCM(aes)
// if err != nil {
// panic(err)
// }
nonceSize := gcm.NonceSize()
nonce, ciphertext := cipherText[:nonceSize], cipherText[nonceSize:]
plaintext, err := gcm.Open(nil, []byte(nonce), []byte(ciphertext), nil)
if err != nil {
panic(err)
}
return string(plaintext)
}