-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.go
56 lines (45 loc) · 1.12 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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"log"
)
func EncryptAES(key []byte, plaintext []byte) ([]byte, error) {
// create cipher
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
log.Fatalf("cipher GCM err: %v", err.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
log.Fatalf("nonce err: %v", err.Error())
}
cipherText := gcm.Seal(nonce, nonce, plaintext, nil)
// return hex string
return cipherText, nil
}
func DecryptAES(key []byte, ciphertext []byte) ([]byte, error) {
//ciphertext, _ := hex.DecodeString(ct)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
log.Fatalf("cipher GCM err: %v", err.Error())
}
nonce := ciphertext[:gcm.NonceSize()]
ciphertext = ciphertext[gcm.NonceSize():]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
log.Fatalf("decrypt file err: %v", err.Error())
}
//fmt.Println("DECRYPTED:", s)
return plainText, nil
}