-
Notifications
You must be signed in to change notification settings - Fork 17
/
crypto.go
58 lines (53 loc) · 1.29 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
package util
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"io"
)
func CreateHash(key string) string {
hasher := sha256.Sum256([]byte(key))
return hex.EncodeToString(hasher[:])
}
func Encrypt(plainText, passphrase string) (string, error) {
key, err := hex.DecodeString(passphrase)
if err != nil {
return "", err
}
block, _ := aes.NewCipher(key)
gcm, err := cipher.NewGCM(block)
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, []byte(plainText), nil)
return base64.StdEncoding.EncodeToString(cipherText), nil
}
func Decrypt(cipherText, passphrase string) (string, error) {
key, err := hex.DecodeString(passphrase)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
ciphertextByte, _ := base64.StdEncoding.DecodeString(cipherText)
nonce, ciphertext := ciphertextByte[:nonceSize], ciphertextByte[nonceSize:]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plainText), nil
}