/
decrypt.go
335 lines (292 loc) · 9.04 KB
/
decrypt.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package jwe
import (
"crypto/aes"
cryptocipher "crypto/cipher"
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"hash"
"golang.org/x/crypto/pbkdf2"
"github.com/lestrrat-go/jwx/internal/keyconv"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwe/internal/cipher"
"github.com/lestrrat-go/jwx/jwe/internal/content_crypt"
"github.com/lestrrat-go/jwx/jwe/internal/keyenc"
"github.com/lestrrat-go/jwx/x25519"
"github.com/lestrrat-go/pdebug/v3"
"github.com/pkg/errors"
)
// Decrypter is responsible for taking various components to decrypt a message.
// its operation is not concurrency safe. You must provide locking yourself
//nolint:govet
type Decrypter struct {
aad []byte
apu []byte
apv []byte
computedAad []byte
iv []byte
keyiv []byte
keysalt []byte
keytag []byte
tag []byte
privkey interface{}
pubkey interface{}
ctalg jwa.ContentEncryptionAlgorithm
keyalg jwa.KeyEncryptionAlgorithm
cipher content_crypt.Cipher
keycount int
}
// NewDecrypter Creates a new Decrypter instance. You must supply the
// rest of parameters via their respective setter methods before
// calling Decrypt().
//
// privkey must be a private key in its "raw" format (i.e. something like
// *rsa.PrivateKey, instead of jwk.Key)
//
// You should consider this object immutable once you assign values to it.
func NewDecrypter(keyalg jwa.KeyEncryptionAlgorithm, ctalg jwa.ContentEncryptionAlgorithm, privkey interface{}) *Decrypter {
return &Decrypter{
ctalg: ctalg,
keyalg: keyalg,
privkey: privkey,
}
}
func (d *Decrypter) AgreementPartyUInfo(apu []byte) *Decrypter {
d.apu = apu
return d
}
func (d *Decrypter) AgreementPartyVInfo(apv []byte) *Decrypter {
d.apv = apv
return d
}
func (d *Decrypter) AuthenticatedData(aad []byte) *Decrypter {
d.aad = aad
return d
}
func (d *Decrypter) ComputedAuthenticatedData(aad []byte) *Decrypter {
d.computedAad = aad
return d
}
func (d *Decrypter) ContentEncryptionAlgorithm(ctalg jwa.ContentEncryptionAlgorithm) *Decrypter {
d.ctalg = ctalg
return d
}
func (d *Decrypter) InitializationVector(iv []byte) *Decrypter {
d.iv = iv
return d
}
func (d *Decrypter) KeyCount(keycount int) *Decrypter {
d.keycount = keycount
return d
}
func (d *Decrypter) KeyInitializationVector(keyiv []byte) *Decrypter {
d.keyiv = keyiv
return d
}
func (d *Decrypter) KeySalt(keysalt []byte) *Decrypter {
d.keysalt = keysalt
return d
}
func (d *Decrypter) KeyTag(keytag []byte) *Decrypter {
d.keytag = keytag
return d
}
// PublicKey sets the public key to be used in decoding EC based encryptions.
// The key must be in its "raw" format (i.e. *ecdsa.PublicKey, instead of jwk.Key)
func (d *Decrypter) PublicKey(pubkey interface{}) *Decrypter {
d.pubkey = pubkey
return d
}
func (d *Decrypter) Tag(tag []byte) *Decrypter {
d.tag = tag
return d
}
func (d *Decrypter) ContentCipher() (content_crypt.Cipher, error) {
if d.cipher == nil {
switch d.ctalg {
case jwa.A128GCM, jwa.A192GCM, jwa.A256GCM, jwa.A128CBC_HS256, jwa.A192CBC_HS384, jwa.A256CBC_HS512:
cipher, err := cipher.NewAES(d.ctalg)
if err != nil {
return nil, errors.Wrapf(err, `failed to build content cipher for %s`, d.ctalg)
}
d.cipher = cipher
default:
return nil, errors.Errorf(`invalid content cipher algorithm (%s)`, d.ctalg)
}
}
return d.cipher, nil
}
func (d *Decrypter) Decrypt(recipientKey, ciphertext []byte) (plaintext []byte, err error) {
if pdebug.Enabled {
g := pdebug.FuncMarker().BindError(&err)
defer g.End()
}
cek, keyerr := d.DecryptKey(recipientKey)
if keyerr != nil {
err = errors.Wrap(keyerr, `failed to decrypt key`)
return
}
cipher, ciphererr := d.ContentCipher()
if ciphererr != nil {
err = errors.Wrap(ciphererr, `failed to fetch content crypt cipher`)
return
}
computedAad := d.computedAad
if d.aad != nil {
computedAad = append(append(computedAad, '.'), d.aad...)
}
if pdebug.Enabled {
pdebug.Printf("Calling cipher.Decrypt (cipher = %T, cek len = %d)", cipher, len(cek))
}
plaintext, err = cipher.Decrypt(cek, d.iv, ciphertext, d.tag, computedAad)
if err != nil {
err = errors.Wrap(err, `failed to decrypt payload`)
return
}
if pdebug.Enabled {
pdebug.Printf("Successfully decrypted payload")
}
return plaintext, nil
}
func (d *Decrypter) decryptSymmetricKey(recipientKey, cek []byte) ([]byte, error) {
if pdebug.Enabled {
pdebug.Printf("Detected symmetric key algorithm %s", d.keyalg)
}
switch d.keyalg {
case jwa.DIRECT:
if pdebug.Enabled {
pdebug.Printf("Successfully decrypted symmetric key (key len = %d)", len(cek))
}
return cek, nil
case jwa.PBES2_HS256_A128KW, jwa.PBES2_HS384_A192KW, jwa.PBES2_HS512_A256KW:
var hashFunc func() hash.Hash
var keylen int
switch d.keyalg {
case jwa.PBES2_HS256_A128KW:
hashFunc = sha256.New
keylen = 16
case jwa.PBES2_HS384_A192KW:
hashFunc = sha512.New384
keylen = 24
case jwa.PBES2_HS512_A256KW:
hashFunc = sha512.New
keylen = 32
}
salt := []byte(d.keyalg)
salt = append(salt, byte(0))
salt = append(salt, d.keysalt...)
cek = pbkdf2.Key(cek, salt, d.keycount, keylen, hashFunc)
fallthrough
case jwa.A128KW, jwa.A192KW, jwa.A256KW:
block, err := aes.NewCipher(cek)
if err != nil {
return nil, errors.Wrap(err, `failed to create new AES cipher`)
}
jek, err := keyenc.Unwrap(block, recipientKey)
if err != nil {
return nil, errors.Wrap(err, `failed to unwrap key`)
}
if pdebug.Enabled {
pdebug.Printf("cek len = %d", len(cek))
pdebug.Printf("Wrapped key len = %d", len(jek))
}
return jek, nil
case jwa.A128GCMKW, jwa.A192GCMKW, jwa.A256GCMKW:
if pdebug.Enabled {
pdebug.Printf("cek len = %d", len(cek))
}
if len(d.keyiv) != 12 {
return nil, errors.Errorf("GCM requires 96-bit iv, got %d", len(d.keyiv)*8)
}
if len(d.keytag) != 16 {
return nil, errors.Errorf("GCM requires 128-bit tag, got %d", len(d.keytag)*8)
}
block, err := aes.NewCipher(cek)
if err != nil {
return nil, errors.Wrap(err, `failed to create new AES cipher`)
}
aesgcm, err := cryptocipher.NewGCM(block)
if err != nil {
return nil, errors.Wrap(err, `failed to create new GCM wrap`)
}
ciphertext := recipientKey[:]
ciphertext = append(ciphertext, d.keytag...)
jek, err := aesgcm.Open(nil, d.keyiv, ciphertext, nil)
if err != nil {
return nil, errors.Wrap(err, `failed to decode key`)
}
return jek, nil
default:
return nil, errors.Errorf("decrypt key: unsupported algorithm %s", d.keyalg)
}
}
func (d *Decrypter) DecryptKey(recipientKey []byte) (cek []byte, err error) {
if pdebug.Enabled {
g := pdebug.FuncMarker().BindError(&err)
defer g.End()
}
if d.keyalg.IsSymmetric() {
var ok bool
cek, ok = d.privkey.([]byte)
if !ok {
return nil, errors.Errorf("decrypt key: []byte is required as the key to build %s key decrypter (got %T)", d.keyalg, d.privkey)
}
return d.decryptSymmetricKey(recipientKey, cek)
}
k, err := d.BuildKeyDecrypter()
if err != nil {
return nil, errors.Wrap(err, `failed to build key decrypter`)
}
cek, err = k.Decrypt(recipientKey)
if err != nil {
return nil, errors.Wrap(err, `failed to decrypt key`)
}
if pdebug.Enabled {
pdebug.Printf("Successfully decrypted key")
}
return cek, nil
}
func (d *Decrypter) BuildKeyDecrypter() (keyenc.Decrypter, error) {
cipher, err := d.ContentCipher()
if err != nil {
return nil, errors.Wrap(err, `failed to fetch content crypt cipher`)
}
switch alg := d.keyalg; alg {
case jwa.RSA1_5:
var privkey rsa.PrivateKey
if err := keyconv.RSAPrivateKey(&privkey, d.privkey); err != nil {
return nil, errors.Wrapf(err, "*rsa.PrivateKey is required as the key to build %s key decrypter", alg)
}
return keyenc.NewRSAPKCS15Decrypt(alg, &privkey, cipher.KeySize()/2), nil
case jwa.RSA_OAEP, jwa.RSA_OAEP_256:
var privkey rsa.PrivateKey
if err := keyconv.RSAPrivateKey(&privkey, d.privkey); err != nil {
return nil, errors.Wrapf(err, "*rsa.PrivateKey is required as the key to build %s key decrypter", alg)
}
return keyenc.NewRSAOAEPDecrypt(alg, &privkey)
case jwa.A128KW, jwa.A192KW, jwa.A256KW:
sharedkey, ok := d.privkey.([]byte)
if !ok {
return nil, errors.Errorf("[]byte is required as the key to build %s key decrypter", alg)
}
return keyenc.NewAES(alg, sharedkey)
case jwa.ECDH_ES, jwa.ECDH_ES_A128KW, jwa.ECDH_ES_A192KW, jwa.ECDH_ES_A256KW:
switch d.pubkey.(type) {
case x25519.PublicKey:
return keyenc.NewECDHESDecrypt(alg, d.ctalg, d.pubkey, d.apu, d.apv, d.privkey), nil
default:
var pubkey ecdsa.PublicKey
if err := keyconv.ECDSAPublicKey(&pubkey, d.pubkey); err != nil {
return nil, errors.Wrapf(err, "*ecdsa.PublicKey is required as the key to build %s key decrypter", alg)
}
var privkey ecdsa.PrivateKey
if err := keyconv.ECDSAPrivateKey(&privkey, d.privkey); err != nil {
return nil, errors.Wrapf(err, "*ecdsa.PrivateKey is required as the key to build %s key decrypter", alg)
}
return keyenc.NewECDHESDecrypt(alg, d.ctalg, &pubkey, d.apu, d.apv, &privkey), nil
}
default:
return nil, errors.Errorf(`unsupported algorithm for key decryption (%s)`, alg)
}
}