-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes-gcm.go
62 lines (50 loc) · 1.24 KB
/
aes-gcm.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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
// Encrypt is used to encrypt a data with a given key.
func Encrypt(secret, data, aad []byte) (encrypted []byte, err error) {
var block cipher.Block
if block, err = aes.NewCipher(secret); err != nil {
return
}
var gcm cipher.AEAD
if gcm, err = cipher.NewGCM(block); err != nil {
return
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return
}
encrypted = gcm.Seal(nonce, nonce, data, aad)
return
}
// Decrypt is used to decrypt a message with a given key, and verify it's contents.
func Decrypt(secret, encrypted, aad []byte) (plain []byte, err error) {
// Ensure we have at least one byte
if len(encrypted) == 0 {
return nil, fmt.Errorf("cannot decrypt empty payload")
}
var block cipher.Block
if block, err = aes.NewCipher(secret); err != nil {
return
}
var gcm cipher.AEAD
if gcm, err = cipher.NewGCM(block); err != nil {
return
}
nonceSize := gcm.NonceSize()
if len(encrypted) < nonceSize {
err = ErrInvalidMessage
return
}
nonce, cipherText := encrypted[:nonceSize], encrypted[nonceSize:]
if plain, err = gcm.Open(nil, nonce, cipherText, aad); err != nil {
return
}
return
}