/
encrypt.go
174 lines (153 loc) · 5.03 KB
/
encrypt.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package jwe
import (
"context"
"sync"
"github.com/lestrrat-go/jwx/internal/base64"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/pdebug/v3"
"github.com/pkg/errors"
)
var encryptCtxPool = sync.Pool{
New: func() interface{} {
return &encryptCtx{}
},
}
func getEncryptCtx() *encryptCtx {
return encryptCtxPool.Get().(*encryptCtx)
}
func releaseEncryptCtx(ctx *encryptCtx) {
ctx.protected = nil
ctx.contentEncrypter = nil
ctx.generator = nil
ctx.keyEncrypters = nil
ctx.compress = jwa.NoCompress
encryptCtxPool.Put(ctx)
}
// Encrypt takes the plaintext and encrypts into a JWE message.
func (e encryptCtx) Encrypt(plaintext []byte) (*Message, error) {
if pdebug.Enabled {
g := pdebug.FuncMarker()
defer g.End()
}
bk, err := e.generator.Generate()
if err != nil {
if pdebug.Enabled {
pdebug.Printf("Failed to generate key: %s", err)
}
return nil, errors.Wrap(err, "failed to generate key")
}
cek := bk.Bytes()
if pdebug.Enabled {
pdebug.Printf("Encrypt: generated cek len = %d", len(cek))
}
if e.protected == nil {
// shouldn't happen, but...
e.protected = NewHeaders()
}
if err := e.protected.Set(ContentEncryptionKey, e.contentEncrypter.Algorithm()); err != nil {
return nil, errors.Wrap(err, `failed to set "enc" in protected header`)
}
compression := e.compress
if compression != jwa.NoCompress {
if err := e.protected.Set(CompressionKey, compression); err != nil {
return nil, errors.Wrap(err, `failed to set "zip" in protected header`)
}
}
// In JWE, multiple recipients may exist -- they receive an
// encrypted version of the CEK, using their key encryption
// algorithm of choice.
recipients := make([]Recipient, len(e.keyEncrypters))
for i, enc := range e.keyEncrypters {
r := NewRecipient()
if err := r.Headers().Set(AlgorithmKey, enc.Algorithm()); err != nil {
return nil, errors.Wrap(err, "failed to set header")
}
if v := enc.KeyID(); v != "" {
if err := r.Headers().Set(KeyIDKey, v); err != nil {
return nil, errors.Wrap(err, "failed to set header")
}
}
enckey, err := enc.Encrypt(cek)
if err != nil {
if pdebug.Enabled {
pdebug.Printf("Failed to encrypt key: %s", err)
}
return nil, errors.Wrap(err, `failed to encrypt key`)
}
if enc.Algorithm() == jwa.ECDH_ES || enc.Algorithm() == jwa.DIRECT {
if len(e.keyEncrypters) > 1 {
return nil, errors.Errorf("unable to support multiple recipients for ECDH-ES")
}
cek = enckey.Bytes()
} else {
if err := r.SetEncryptedKey(enckey.Bytes()); err != nil {
return nil, errors.Wrap(err, "failed to set encrypted key")
}
}
if hp, ok := enckey.(populater); ok {
if err := hp.Populate(r.Headers()); err != nil {
return nil, errors.Wrap(err, "failed to populate")
}
}
if pdebug.Enabled {
pdebug.Printf("Encrypt: encrypted_key = %x (%d)", enckey.Bytes(), len(enckey.Bytes()))
}
recipients[i] = r
}
// If there's only one recipient, you want to include that in the
// protected header
if len(recipients) == 1 {
h, err := e.protected.Merge(context.TODO(), recipients[0].Headers())
if err != nil {
return nil, errors.Wrap(err, "failed to merge protected headers")
}
e.protected = h
}
aad, err := e.protected.Encode()
if err != nil {
return nil, errors.Wrap(err, "failed to base64 encode protected headers")
}
plaintext, err = compress(plaintext, compression)
if err != nil {
return nil, errors.Wrap(err, `failed to compress payload before encryption`)
}
// ...on the other hand, there's only one content cipher.
iv, ciphertext, tag, err := e.contentEncrypter.Encrypt(cek, plaintext, aad)
if err != nil {
if pdebug.Enabled {
pdebug.Printf("Failed to encrypt: %s", err)
}
return nil, errors.Wrap(err, "failed to encrypt payload")
}
if pdebug.Enabled {
pdebug.Printf("Encrypt.Encrypt: cek = %x (%d)", cek, len(cek))
pdebug.Printf("Encrypt.Encrypt: aad = %x (%d)", aad, len(aad))
pdebug.Printf("Encrypt.Encrypt: ciphertext = %x (%d)", ciphertext, len(ciphertext))
pdebug.Printf("Encrypt.Encrypt: iv = %x (%d)", iv, len(iv))
pdebug.Printf("Encrypt.Encrypt: tag = %x (%d)", tag, len(tag))
}
msg := NewMessage()
decodedAad, err := base64.Decode(aad)
if err != nil {
return nil, errors.Wrap(err, "failed to decode base64")
}
if err := msg.Set(AuthenticatedDataKey, decodedAad); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, AuthenticatedDataKey)
}
if err := msg.Set(CipherTextKey, ciphertext); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, CipherTextKey)
}
if err := msg.Set(InitializationVectorKey, iv); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, InitializationVectorKey)
}
if err := msg.Set(ProtectedHeadersKey, e.protected); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, ProtectedHeadersKey)
}
if err := msg.Set(RecipientsKey, recipients); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, RecipientsKey)
}
if err := msg.Set(TagKey, tag); err != nil {
return nil, errors.Wrapf(err, `failed to set %s`, TagKey)
}
return msg, nil
}