Debian Codegraph @

crypter.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package jose
18
19 import (
20 "crypto/ecdsa"
21 "crypto/rsa"
22 "errors"
23 "fmt"
24 "reflect"
25 )
26
27 // Encrypter represents an encrypter which produces an encrypted JWE object.
28 type Encrypter interface {
29 Encrypt(plaintext []byte) (*JsonWebEncryption, error)
30 EncryptWithAuthData(plaintext []byte, aad []byte) (*JsonWebEncryption, error)
31 SetCompression(alg CompressionAlgorithm)
32 }
33
34 // MultiEncrypter represents an encrypter which supports multiple recipients.
35 type MultiEncrypter interface {
36 Encrypt(plaintext []byte) (*JsonWebEncryption, error)
37 EncryptWithAuthData(plaintext []byte, aad []byte) (*JsonWebEncryption, error)
38 SetCompression(alg CompressionAlgorithm)
39 AddRecipient(alg KeyAlgorithm, encryptionKey interface{}) error
40 }
41
42 // A generic content cipher
43 type contentCipher interface {
44 keySize() int
45 encrypt(cek []byte, aad, plaintext []byte) (*aeadParts, error)
46 decrypt(cek []byte, aad []byte, parts *aeadParts) ([]byte, error)
47 }
48
49 // A key generator (for generating/getting a CEK)
50 type keyGenerator interface {
51 keySize() int
52 genKey() ([]byte, rawHeader, error)
53 }
54
55 // A generic key encrypter
56 type keyEncrypter interface {
57 encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error) // Encrypt a key
58 }
59
60 // A generic key decrypter
61 type keyDecrypter interface {
62 decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) // Decrypt a key
63 }
64
65 // A generic encrypter based on the given key encrypter and content cipher.
66 type genericEncrypter struct {
67 contentAlg ContentEncryption
68 compressionAlg CompressionAlgorithm
69 cipher contentCipher
70 recipients []recipientKeyInfo
71 keyGenerator keyGenerator
72 }
73
74 type recipientKeyInfo struct {
75 keyID string
76 keyAlg KeyAlgorithm
77 keyEncrypter keyEncrypter
78 }
79
80 // SetCompression sets a compression algorithm to be applied before encryption.
81 func (ctx *genericEncrypter) SetCompression(compressionAlg CompressionAlgorithm) {
82 ctx.compressionAlg = compressionAlg
83 }
84
85 // NewEncrypter creates an appropriate encrypter based on the key type
86 func NewEncrypter(alg KeyAlgorithm, enc ContentEncryption, encryptionKey interface{}) (Encrypter, error) {
87 encrypter := &genericEncrypter{
88 contentAlg: enc,
89 compressionAlg: NONE,
90 recipients: []recipientKeyInfo{},
91 cipher: getContentCipher(enc),
92 }
93
94 if encrypter.cipher == nil {
95 return nil, ErrUnsupportedAlgorithm
96 }
97
98 var keyID string
99 var rawKey interface{}
100 switch encryptionKey := encryptionKey.(type) {
101 case *JsonWebKey:
102 keyID = encryptionKey.KeyID
103 rawKey = encryptionKey.Key
104 default:
105 rawKey = encryptionKey
106 }
107
108 switch alg {
109 case DIRECT:
110 // Direct encryption mode must be treated differently
111 if reflect.TypeOf(rawKey) != reflect.TypeOf([]byte{}) {
112 return nil, ErrUnsupportedKeyType
113 }
114 encrypter.keyGenerator = staticKeyGenerator{
115 key: rawKey.([]byte),
116 }
117 recipient, _ := newSymmetricRecipient(alg, rawKey.([]byte))
118 if keyID != "" {
119 recipient.keyID = keyID
120 }
121 encrypter.recipients = []recipientKeyInfo{recipient}
122 return encrypter, nil
123 case ECDH_ES:
124 // ECDH-ES (w/o key wrapping) is similar to DIRECT mode
125 typeOf := reflect.TypeOf(rawKey)
126 if typeOf != reflect.TypeOf(&ecdsa.PublicKey{}) {
127 return nil, ErrUnsupportedKeyType
128 }
129 encrypter.keyGenerator = ecKeyGenerator{
130 size: encrypter.cipher.keySize(),
131 algID: string(enc),
132 publicKey: rawKey.(*ecdsa.PublicKey),
133 }
134 recipient, _ := newECDHRecipient(alg, rawKey.(*ecdsa.PublicKey))
135 if keyID != "" {
136 recipient.keyID = keyID
137 }
138 encrypter.recipients = []recipientKeyInfo{recipient}
139 return encrypter, nil
140 default:
141 // Can just add a standard recipient
142 encrypter.keyGenerator = randomKeyGenerator{
143 size: encrypter.cipher.keySize(),
144 }
145 err := encrypter.AddRecipient(alg, encryptionKey)
146 return encrypter, err
147 }
148 }
149
150 // NewMultiEncrypter creates a multi-encrypter based on the given parameters
151 func NewMultiEncrypter(enc ContentEncryption) (MultiEncrypter, error) {
152 cipher := getContentCipher(enc)
153
154 if cipher == nil {
155 return nil, ErrUnsupportedAlgorithm
156 }
157
158 encrypter := &genericEncrypter{
159 contentAlg: enc,
160 compressionAlg: NONE,
161 recipients: []recipientKeyInfo{},
162 cipher: cipher,
163 keyGenerator: randomKeyGenerator{
164 size: cipher.keySize(),
165 },
166 }
167
168 return encrypter, nil
169 }
170
171 func (ctx *genericEncrypter) AddRecipient(alg KeyAlgorithm, encryptionKey interface{}) (err error) {
172 var recipient recipientKeyInfo
173
174 switch alg {
175 case DIRECT, ECDH_ES:
176 return fmt.Errorf("square/go-jose: key algorithm '%s' not supported in multi-recipient mode", alg)
177 }
178
179 recipient, err = makeJWERecipient(alg, encryptionKey)
180
181 if err == nil {
182 ctx.recipients = append(ctx.recipients, recipient)
183 }
184 return err
185 }
186
187 func makeJWERecipient(alg KeyAlgorithm, encryptionKey interface{}) (recipientKeyInfo, error) {
188 switch encryptionKey := encryptionKey.(type) {
189 case *rsa.PublicKey:
190 return newRSARecipient(alg, encryptionKey)
191 case *ecdsa.PublicKey:
192 return newECDHRecipient(alg, encryptionKey)
193 case []byte:
194 return newSymmetricRecipient(alg, encryptionKey)
195 case *JsonWebKey:
196 recipient, err := makeJWERecipient(alg, encryptionKey.Key)
197 if err == nil && encryptionKey.KeyID != "" {
198 recipient.keyID = encryptionKey.KeyID
199 }
200 return recipient, err
201 default:
202 return recipientKeyInfo{}, ErrUnsupportedKeyType
203 }
204 }
205
206 // newDecrypter creates an appropriate decrypter based on the key type
207 func newDecrypter(decryptionKey interface{}) (keyDecrypter, error) {
208 switch decryptionKey := decryptionKey.(type) {
209 case *rsa.PrivateKey:
210 return &rsaDecrypterSigner{
211 privateKey: decryptionKey,
212 }, nil
213 case *ecdsa.PrivateKey:
214 return &ecDecrypterSigner{
215 privateKey: decryptionKey,
216 }, nil
217 case []byte:
218 return &symmetricKeyCipher{
219 key: decryptionKey,
220 }, nil
221 case *JsonWebKey:
222 return newDecrypter(decryptionKey.Key)
223 default:
224 return nil, ErrUnsupportedKeyType
225 }
226 }
227
228 // Implementation of encrypt method producing a JWE object.
229 func (ctx *genericEncrypter) Encrypt(plaintext []byte) (*JsonWebEncryption, error) {
230 return ctx.EncryptWithAuthData(plaintext, nil)
231 }
232
233 // Implementation of encrypt method producing a JWE object.
234 func (ctx *genericEncrypter) EncryptWithAuthData(plaintext, aad []byte) (*JsonWebEncryption, error) {
235 obj := &JsonWebEncryption{}
236 obj.aad = aad
237
238 obj.protected = &rawHeader{
239 Enc: ctx.contentAlg,
240 }
241 obj.recipients = make([]recipientInfo, len(ctx.recipients))
242
243 if len(ctx.recipients) == 0 {
244 return nil, fmt.Errorf("square/go-jose: no recipients to encrypt to")
245 }
246
247 cek, headers, err := ctx.keyGenerator.genKey()
248 if err != nil {
249 return nil, err
250 }
251
252 obj.protected.merge(&headers)
253
254 for i, info := range ctx.recipients {
255 recipient, err := info.keyEncrypter.encryptKey(cek, info.keyAlg)
256 if err != nil {
257 return nil, err
258 }
259
260 recipient.header.Alg = string(info.keyAlg)
261 if info.keyID != "" {
262 recipient.header.Kid = info.keyID
263 }
264 obj.recipients[i] = recipient
265 }
266
267 if len(ctx.recipients) == 1 {
268 // Move per-recipient headers into main protected header if there's
269 // only a single recipient.
270 obj.protected.merge(obj.recipients[0].header)
271 obj.recipients[0].header = nil
272 }
273
274 if ctx.compressionAlg != NONE {
275 plaintext, err = compress(ctx.compressionAlg, plaintext)
276 if err != nil {
277 return nil, err
278 }
279
280 obj.protected.Zip = ctx.compressionAlg
281 }
282
283 authData := obj.computeAuthData()
284 parts, err := ctx.cipher.encrypt(cek, authData, plaintext)
285 if err != nil {
286 return nil, err
287 }
288
289 obj.iv = parts.iv
290 obj.ciphertext = parts.ciphertext
291 obj.tag = parts.tag
292
293 return obj, nil
294 }
295
296 // Decrypt and validate the object and return the plaintext. Note that this
297 // function does not support multi-recipient, if you desire multi-recipient
298 // decryption use DecryptMulti instead.
299 func (obj JsonWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error) {
300 headers := obj.mergedHeaders(nil)
301
302 if len(obj.recipients) > 1 {
303 return nil, errors.New("square/go-jose: too many recipients in payload; expecting only one")
304 }
305
306 if len(headers.Crit) > 0 {
307 return nil, fmt.Errorf("square/go-jose: unsupported crit header")
308 }
309
310 decrypter, err := newDecrypter(decryptionKey)
311 if err != nil {
312 return nil, err
313 }
314
315 cipher := getContentCipher(headers.Enc)
316 if cipher == nil {
317 return nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(headers.Enc))
318 }
319
320 generator := randomKeyGenerator{
321 size: cipher.keySize(),
322 }
323
324 parts := &aeadParts{
325 iv: obj.iv,
326 ciphertext: obj.ciphertext,
327 tag: obj.tag,
328 }
329
330 authData := obj.computeAuthData()
331
332 var plaintext []byte
333 recipient := obj.recipients[0]
334 recipientHeaders := obj.mergedHeaders(&recipient)
335
336 cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
337 if err == nil {
338 // Found a valid CEK -- let's try to decrypt.
339 plaintext, err = cipher.decrypt(cek, authData, parts)
340 }
341
342 if plaintext == nil {
343 return nil, ErrCryptoFailure
344 }
345
346 // The "zip" header parameter may only be present in the protected header.
347 if obj.protected.Zip != "" {
348 plaintext, err = decompress(obj.protected.Zip, plaintext)
349 }
350
351 return plaintext, err
352 }
353
354 // DecryptMulti decrypts and validates the object and returns the plaintexts,
355 // with support for multiple recipients. It returns the index of the recipient
356 // for which the decryption was successful, the merged headers for that recipient,
357 // and the plaintext.
358 func (obj JsonWebEncryption) DecryptMulti(decryptionKey interface{}) (int, JoseHeader, []byte, error) {
359 globalHeaders := obj.mergedHeaders(nil)
360
361 if len(globalHeaders.Crit) > 0 {
362 return -1, JoseHeader{}, nil, fmt.Errorf("square/go-jose: unsupported crit header")
363 }
364
365 decrypter, err := newDecrypter(decryptionKey)
366 if err != nil {
367 return -1, JoseHeader{}, nil, err
368 }
369
370 cipher := getContentCipher(globalHeaders.Enc)
371 if cipher == nil {
372 return -1, JoseHeader{}, nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(globalHeaders.Enc))
373 }
374
375 generator := randomKeyGenerator{
376 size: cipher.keySize(),
377 }
378
379 parts := &aeadParts{
380 iv: obj.iv,
381 ciphertext: obj.ciphertext,
382 tag: obj.tag,
383 }
384
385 authData := obj.computeAuthData()
386
387 index := -1
388 var plaintext []byte
389 var headers rawHeader
390
391 for i, recipient := range obj.recipients {
392 recipientHeaders := obj.mergedHeaders(&recipient)
393
394 cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
395 if err == nil {
396 // Found a valid CEK -- let's try to decrypt.
397 plaintext, err = cipher.decrypt(cek, authData, parts)
398 if err == nil {
399 index = i
400 headers = recipientHeaders
401 break
402 }
403 }
404 }
405
406 if plaintext == nil || err != nil {
407 return -1, JoseHeader{}, nil, ErrCryptoFailure
408 }
409
410 // The "zip" header parameter may only be present in the protected header.
411 if obj.protected.Zip != "" {
412 plaintext, err = decompress(obj.protected.Zip, plaintext)
413 }
414
415 return index, headers.sanitized(), plaintext, err
416 }