-
Notifications
You must be signed in to change notification settings - Fork 0
/
aead.go
56 lines (45 loc) · 1.02 KB
/
aead.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 aead
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"github.com/ssh-vault/crypto"
)
// Encrypt AES-256 GCM
func Encrypt(password, message, additionalData []byte) ([]byte, error) {
if len(password) != 32 {
return nil, fmt.Errorf("key size %d != 32", len(password))
}
c, err := aes.NewCipher(password)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce, err := crypto.GenerateNonce(gcm.NonceSize())
if err != nil {
return nil, err
}
out := gcm.Seal(nonce, nonce, message, additionalData)
return out, nil
}
// Decrypt AES-256 GCM
func Decrypt(password, message, additionalData []byte) ([]byte, error) {
c, err := aes.NewCipher(password)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
copy(nonce, message[:gcm.NonceSize()])
out, err := gcm.Open(nil, nonce, message[gcm.NonceSize():], additionalData)
if err != nil {
return nil, err
}
return out, nil
}