forked from hashicorp/go-kms-wrapping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envelope.go
101 lines (87 loc) · 2.52 KB
/
envelope.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package wrapping
import (
"crypto/aes"
"crypto/cipher"
"errors"
fmt "fmt"
uuid "github.com/hashicorp/go-uuid"
)
// EnvelopeEncrypt takes in plaintext and envelope encrypts it, generating an
// EnvelopeInfo value. An empty plaintext is a valid parameter and will not cause
// an error. Also note: if you provide a plaintext of []byte(""),
// EnvelopeDecrypt will return []byte(nil).
//
// Supported options:
//
// * wrapping.WithAad: Additional authenticated data that should be sourced from
// a separate location, and must also be provided during envelope decryption
func EnvelopeEncrypt(plaintext []byte, opt ...Option) (*EnvelopeInfo, error) {
opts, err := GetOpts(opt...)
if err != nil {
return nil, err
}
// Generate DEK
key, err := uuid.GenerateRandomBytes(32)
if err != nil {
return nil, err
}
var iv []byte
if opts.WithIv != nil {
if len(opts.WithIv) != 12 {
return nil, fmt.Errorf("invalid IV provided: expected 12 bytes, got %d", len(opts.WithIv))
}
iv = opts.WithIv
} else {
iv, err = uuid.GenerateRandomBytes(12)
if err != nil {
return nil, err
}
}
aead, err := aeadEncrypter(key)
if err != nil {
return nil, err
}
return &EnvelopeInfo{
Ciphertext: aead.Seal(nil, iv, plaintext, opts.WithAad),
Key: key,
Iv: iv,
}, nil
}
// EnvelopeDecrypt takes in EnvelopeInfo and potentially additional options and
// decrypts. Also note: if you provided a plaintext of []byte("") to
// EnvelopeEncrypt, then this function will return []byte(nil).
//
// Supported options:
//
// * wrapping.WithAad: Additional authenticated data that should be sourced from
// a separate location, and must match what was provided during envelope
// encryption.
func EnvelopeDecrypt(data *EnvelopeInfo, opt ...Option) ([]byte, error) {
// need to check data or we could panic when trying to access data.Key
if data == nil {
return nil, fmt.Errorf("missing envelope info: %w", ErrInvalidParameter)
}
opts, err := GetOpts(opt...)
if err != nil {
return nil, err
}
aead, err := aeadEncrypter(data.Key)
if err != nil {
return nil, err
}
return aead.Open(nil, data.Iv, data.Ciphertext, opts.WithAad)
}
func aeadEncrypter(key []byte) (cipher.AEAD, error) {
aesCipher, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create cipher: %w", err)
}
// Create the GCM mode AEAD
gcm, err := cipher.NewGCM(aesCipher)
if err != nil {
return nil, errors.New("failed to initialize GCM mode")
}
return gcm, nil
}