-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.go
More file actions
72 lines (65 loc) · 1.46 KB
/
Copy pathcrypto.go
File metadata and controls
72 lines (65 loc) · 1.46 KB
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
63
64
65
66
67
68
69
70
71
72
package cryptlite
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
const (
keySize = 32 // AES-256
nonceSize = 12 // GCM standard nonce
)
// EncryptedBlob holds the output of a single encryption operation.
type EncryptedBlob struct {
Ciphertext []byte
Nonce []byte
KeyVersion int
}
func generateKey() ([]byte, error) {
key := make([]byte, keySize)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return nil, err
}
return key, nil
}
func generateNonce() ([]byte, error) {
nonce := make([]byte, nonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return nonce, nil
}
func encrypt(key []byte, plaintext, aad []byte) (ciphertext, nonce []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, nil, err
}
nonce, err = generateNonce()
if err != nil {
return nil, nil, err
}
ciphertext = gcm.Seal(nil, nonce, plaintext, aad)
return ciphertext, nonce, nil
}
func decrypt(key, ciphertext, nonce, aad []byte) ([]byte, error) {
if len(ciphertext) == 0 || len(nonce) != nonceSize {
return nil, ErrInvalidCiphertext
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
plaintext, err := gcm.Open(nil, nonce, ciphertext, aad)
if err != nil {
return nil, ErrInvalidCiphertext
}
return plaintext, nil
}