-
Notifications
You must be signed in to change notification settings - Fork 2
/
encryption.go
55 lines (45 loc) · 969 Bytes
/
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
package sicher
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"io"
)
// encrypt encrypts the given plaintext with the given key and returns the ciphertext
func encrypt(key string, fileData []byte) (nonce []byte, ciphertext []byte, err error) {
hKey, err := hex.DecodeString(key)
if err != nil {
return
}
block, err := aes.NewCipher(hKey)
if err != nil {
return
}
nonce = make([]byte, 12)
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return
}
ciphertext = aesgcm.Seal(nil, nonce, fileData, nil)
return
}
func decrypt(key string, nonce, text []byte) (plaintext []byte, err error) {
hKey, err := hex.DecodeString(key)
if err != nil {
return
}
block, err := aes.NewCipher(hKey)
if err != nil {
return
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return
}
plaintext, err = aesgcm.Open(nil, nonce, text, nil)
return
}