-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryptor.go
More file actions
69 lines (56 loc) · 1.8 KB
/
Copy pathencryptor.go
File metadata and controls
69 lines (56 loc) · 1.8 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
// Package crypto provides AES-256-GCM encryption for Vault secrets.
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
)
// ErrInvalidKeySize is returned when the key is not exactly 32 bytes.
var ErrInvalidKeySize = errors.New("crypto: key must be exactly 32 bytes for AES-256")
// Encryptor provides AES-256-GCM encryption and decryption.
type Encryptor struct {
aead cipher.AEAD
}
// NewEncryptor creates an Encryptor from a 32-byte AES-256 key.
func NewEncryptor(key []byte) (*Encryptor, error) {
if len(key) != 32 {
return nil, ErrInvalidKeySize
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("crypto: new cipher: %w", err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("crypto: new gcm: %w", err)
}
return &Encryptor{aead: aead}, nil
}
// Encrypt encrypts plaintext using AES-256-GCM.
// The returned ciphertext has the random nonce prepended: nonce || ciphertext.
func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
nonce := make([]byte, e.aead.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("crypto: generate nonce: %w", err)
}
// Seal appends encrypted data to nonce.
return e.aead.Seal(nonce, nonce, plaintext, nil), nil
}
// Decrypt decrypts ciphertext produced by Encrypt.
// It expects the nonce prepended: nonce || ciphertext.
func (e *Encryptor) Decrypt(ciphertext []byte) ([]byte, error) {
nonceSize := e.aead.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("crypto: ciphertext too short")
}
nonce := ciphertext[:nonceSize]
ct := ciphertext[nonceSize:]
plaintext, err := e.aead.Open(nil, nonce, ct, nil)
if err != nil {
return nil, fmt.Errorf("crypto: decrypt: %w", err)
}
return plaintext, nil
}