Debian Codegraph @

asymmetric.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"
21 "crypto/aes"
22 "crypto/ecdsa"
23 "crypto/rand"
24 "crypto/rsa"
25 "crypto/sha1"
26 "crypto/sha256"
27 "errors"
28 "fmt"
29 "math/big"
30
31 "gopkg.in/square/go-jose.v1/cipher"
32 )
33
34 // A generic RSA-based encrypter/verifier
35 type rsaEncrypterVerifier struct {
36 publicKey *rsa.PublicKey
37 }
38
39 // A generic RSA-based decrypter/signer
40 type rsaDecrypterSigner struct {
41 privateKey *rsa.PrivateKey
42 }
43
44 // A generic EC-based encrypter/verifier
45 type ecEncrypterVerifier struct {
46 publicKey *ecdsa.PublicKey
47 }
48
49 // A key generator for ECDH-ES
50 type ecKeyGenerator struct {
51 size int
52 algID string
53 publicKey *ecdsa.PublicKey
54 }
55
56 // A generic EC-based decrypter/signer
57 type ecDecrypterSigner struct {
58 privateKey *ecdsa.PrivateKey
59 }
60
61 // newRSARecipient creates recipientKeyInfo based on the given key.
62 func newRSARecipient(keyAlg KeyAlgorithm, publicKey *rsa.PublicKey) (recipientKeyInfo, error) {
63 // Verify that key management algorithm is supported by this encrypter
64 switch keyAlg {
65 case RSA1_5, RSA_OAEP, RSA_OAEP_256:
66 default:
67 return recipientKeyInfo{}, ErrUnsupportedAlgorithm
68 }
69
70 if publicKey == nil {
71 return recipientKeyInfo{}, errors.New("invalid public key")
72 }
73
74 return recipientKeyInfo{
75 keyAlg: keyAlg,
76 keyEncrypter: &rsaEncrypterVerifier{
77 publicKey: publicKey,
78 },
79 }, nil
80 }
81
82 // newRSASigner creates a recipientSigInfo based on the given key.
83 func newRSASigner(sigAlg SignatureAlgorithm, privateKey *rsa.PrivateKey) (recipientSigInfo, error) {
84 // Verify that key management algorithm is supported by this encrypter
85 switch sigAlg {
86 case RS256, RS384, RS512, PS256, PS384, PS512:
87 default:
88 return recipientSigInfo{}, ErrUnsupportedAlgorithm
89 }
90
91 if privateKey == nil {
92 return recipientSigInfo{}, errors.New("invalid private key")
93 }
94
95 return recipientSigInfo{
96 sigAlg: sigAlg,
97 publicKey: &JsonWebKey{
98 Key: &privateKey.PublicKey,
99 },
100 signer: &rsaDecrypterSigner{
101 privateKey: privateKey,
102 },
103 }, nil
104 }
105
106 // newECDHRecipient creates recipientKeyInfo based on the given key.
107 func newECDHRecipient(keyAlg KeyAlgorithm, publicKey *ecdsa.PublicKey) (recipientKeyInfo, error) {
108 // Verify that key management algorithm is supported by this encrypter
109 switch keyAlg {
110 case ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW:
111 default:
112 return recipientKeyInfo{}, ErrUnsupportedAlgorithm
113 }
114
115 if publicKey == nil || !publicKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) {
116 return recipientKeyInfo{}, errors.New("invalid public key")
117 }
118
119 return recipientKeyInfo{
120 keyAlg: keyAlg,
121 keyEncrypter: &ecEncrypterVerifier{
122 publicKey: publicKey,
123 },
124 }, nil
125 }
126
127 // newECDSASigner creates a recipientSigInfo based on the given key.
128 func newECDSASigner(sigAlg SignatureAlgorithm, privateKey *ecdsa.PrivateKey) (recipientSigInfo, error) {
129 // Verify that key management algorithm is supported by this encrypter
130 switch sigAlg {
131 case ES256, ES384, ES512:
132 default:
133 return recipientSigInfo{}, ErrUnsupportedAlgorithm
134 }
135
136 if privateKey == nil {
137 return recipientSigInfo{}, errors.New("invalid private key")
138 }
139
140 return recipientSigInfo{
141 sigAlg: sigAlg,
142 publicKey: &JsonWebKey{
143 Key: &privateKey.PublicKey,
144 },
145 signer: &ecDecrypterSigner{
146 privateKey: privateKey,
147 },
148 }, nil
149 }
150
151 // Encrypt the given payload and update the object.
152 func (ctx rsaEncrypterVerifier) encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error) {
153 encryptedKey, err := ctx.encrypt(cek, alg)
154 if err != nil {
155 return recipientInfo{}, err
156 }
157
158 return recipientInfo{
159 encryptedKey: encryptedKey,
160 header: &rawHeader{},
161 }, nil
162 }
163
164 // Encrypt the given payload. Based on the key encryption algorithm,
165 // this will either use RSA-PKCS1v1.5 or RSA-OAEP (with SHA-1 or SHA-256).
166 func (ctx rsaEncrypterVerifier) encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) {
167 switch alg {
168 case RSA1_5:
169 return rsa.EncryptPKCS1v15(randReader, ctx.publicKey, cek)
170 case RSA_OAEP:
171 return rsa.EncryptOAEP(sha1.New(), randReader, ctx.publicKey, cek, []byte{})
172 case RSA_OAEP_256:
173 return rsa.EncryptOAEP(sha256.New(), randReader, ctx.publicKey, cek, []byte{})
174 }
175
176 return nil, ErrUnsupportedAlgorithm
177 }
178
179 // Decrypt the given payload and return the content encryption key.
180 func (ctx rsaDecrypterSigner) decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) {
181 return ctx.decrypt(recipient.encryptedKey, KeyAlgorithm(headers.Alg), generator)
182 }
183
184 // Decrypt the given payload. Based on the key encryption algorithm,
185 // this will either use RSA-PKCS1v1.5 or RSA-OAEP (with SHA-1 or SHA-256).
186 func (ctx rsaDecrypterSigner) decrypt(jek []byte, alg KeyAlgorithm, generator keyGenerator) ([]byte, error) {
187 // Note: The random reader on decrypt operations is only used for blinding,
188 // so stubbing is meanlingless (hence the direct use of rand.Reader).
189 switch alg {
190 case RSA1_5:
191 defer func() {
192 // DecryptPKCS1v15SessionKey sometimes panics on an invalid payload
193 // because of an index out of bounds error, which we want to ignore.
194 // This has been fixed in Go 1.3.1 (released 2014/08/13), the recover()
195 // only exists for preventing crashes with unpatched versions.
196 // See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k
197 // See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33
198 _ = recover()
199 }()
200
201 // Perform some input validation.
202 keyBytes := ctx.privateKey.PublicKey.N.BitLen() / 8
203 if keyBytes != len(jek) {
204 // Input size is incorrect, the encrypted payload should always match
205 // the size of the public modulus (e.g. using a 2048 bit key will
206 // produce 256 bytes of output). Reject this since it's invalid input.
207 return nil, ErrCryptoFailure
208 }
209
210 cek, _, err := generator.genKey()
211 if err != nil {
212 return nil, ErrCryptoFailure
213 }
214
215 // When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to
216 // prevent chosen-ciphertext attacks as described in RFC 3218, "Preventing
217 // the Million Message Attack on Cryptographic Message Syntax". We are
218 // therefore deliberately ignoring errors here.
219 _ = rsa.DecryptPKCS1v15SessionKey(rand.Reader, ctx.privateKey, jek, cek)
220
221 return cek, nil
222 case RSA_OAEP:
223 // Use rand.Reader for RSA blinding
224 return rsa.DecryptOAEP(sha1.New(), rand.Reader, ctx.privateKey, jek, []byte{})
225 case RSA_OAEP_256:
226 // Use rand.Reader for RSA blinding
227 return rsa.DecryptOAEP(sha256.New(), rand.Reader, ctx.privateKey, jek, []byte{})
228 }
229
230 return nil, ErrUnsupportedAlgorithm
231 }
232
233 // Sign the given payload
234 func (ctx rsaDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) {
235 var hash crypto.Hash
236
237 switch alg {
238 case RS256, PS256:
239 hash = crypto.SHA256
240 case RS384, PS384:
241 hash = crypto.SHA384
242 case RS512, PS512:
243 hash = crypto.SHA512
244 default:
245 return Signature{}, ErrUnsupportedAlgorithm
246 }
247
248 hasher := hash.New()
249
250 // According to documentation, Write() on hash never fails
251 _, _ = hasher.Write(payload)
252 hashed := hasher.Sum(nil)
253
254 var out []byte
255 var err error
256
257 switch alg {
258 case RS256, RS384, RS512:
259 out, err = rsa.SignPKCS1v15(randReader, ctx.privateKey, hash, hashed)
260 case PS256, PS384, PS512:
261 out, err = rsa.SignPSS(randReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
262 SaltLength: rsa.PSSSaltLengthAuto,
263 })
264 }
265
266 if err != nil {
267 return Signature{}, err
268 }
269
270 return Signature{
271 Signature: out,
272 protected: &rawHeader{},
273 }, nil
274 }
275
276 // Verify the given payload
277 func (ctx rsaEncrypterVerifier) verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error {
278 var hash crypto.Hash
279
280 switch alg {
281 case RS256, PS256:
282 hash = crypto.SHA256
283 case RS384, PS384:
284 hash = crypto.SHA384
285 case RS512, PS512:
286 hash = crypto.SHA512
287 default:
288 return ErrUnsupportedAlgorithm
289 }
290
291 hasher := hash.New()
292
293 // According to documentation, Write() on hash never fails
294 _, _ = hasher.Write(payload)
295 hashed := hasher.Sum(nil)
296
297 switch alg {
298 case RS256, RS384, RS512:
299 return rsa.VerifyPKCS1v15(ctx.publicKey, hash, hashed, signature)
300 case PS256, PS384, PS512:
301 return rsa.VerifyPSS(ctx.publicKey, hash, hashed, signature, nil)
302 }
303
304 return ErrUnsupportedAlgorithm
305 }
306
307 // Encrypt the given payload and update the object.
308 func (ctx ecEncrypterVerifier) encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error) {
309 switch alg {
310 case ECDH_ES:
311 // ECDH-ES mode doesn't wrap a key, the shared secret is used directly as the key.
312 return recipientInfo{
313 header: &rawHeader{},
314 }, nil
315 case ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW:
316 default:
317 return recipientInfo{}, ErrUnsupportedAlgorithm
318 }
319
320 generator := ecKeyGenerator{
321 algID: string(alg),
322 publicKey: ctx.publicKey,
323 }
324
325 switch alg {
326 case ECDH_ES_A128KW:
327 generator.size = 16
328 case ECDH_ES_A192KW:
329 generator.size = 24
330 case ECDH_ES_A256KW:
331 generator.size = 32
332 }
333
334 kek, header, err := generator.genKey()
335 if err != nil {
336 return recipientInfo{}, err
337 }
338
339 block, err := aes.NewCipher(kek)
340 if err != nil {
341 return recipientInfo{}, err
342 }
343
344 jek, err := josecipher.KeyWrap(block, cek)
345 if err != nil {
346 return recipientInfo{}, err
347 }
348
349 return recipientInfo{
350 encryptedKey: jek,
351 header: &header,
352 }, nil
353 }
354
355 // Get key size for EC key generator
356 func (ctx ecKeyGenerator) keySize() int {
357 return ctx.size
358 }
359
360 // Get a content encryption key for ECDH-ES
361 func (ctx ecKeyGenerator) genKey() ([]byte, rawHeader, error) {
362 priv, err := ecdsa.GenerateKey(ctx.publicKey.Curve, randReader)
363 if err != nil {
364 return nil, rawHeader{}, err
365 }
366
367 out := josecipher.DeriveECDHES(ctx.algID, []byte{}, []byte{}, priv, ctx.publicKey, ctx.size)
368
369 headers := rawHeader{
370 Epk: &JsonWebKey{
371 Key: &priv.PublicKey,
372 },
373 }
374
375 return out, headers, nil
376 }
377
378 // Decrypt the given payload and return the content encryption key.
379 func (ctx ecDecrypterSigner) decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) {
380 if headers.Epk == nil {
381 return nil, errors.New("square/go-jose: missing epk header")
382 }
383
384 publicKey, ok := headers.Epk.Key.(*ecdsa.PublicKey)
385 if publicKey == nil || !ok {
386 return nil, errors.New("square/go-jose: invalid epk header")
387 }
388
389 if !ctx.privateKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) {
390 return nil, errors.New("square/go-jose: invalid public key in epk header")
391 }
392
393 apuData := headers.Apu.bytes()
394 apvData := headers.Apv.bytes()
395
396 deriveKey := func(algID string, size int) []byte {
397 return josecipher.DeriveECDHES(algID, apuData, apvData, ctx.privateKey, publicKey, size)
398 }
399
400 var keySize int
401
402 switch KeyAlgorithm(headers.Alg) {
403 case ECDH_ES:
404 // ECDH-ES uses direct key agreement, no key unwrapping necessary.
405 return deriveKey(string(headers.Enc), generator.keySize()), nil
406 case ECDH_ES_A128KW:
407 keySize = 16
408 case ECDH_ES_A192KW:
409 keySize = 24
410 case ECDH_ES_A256KW:
411 keySize = 32
412 default:
413 return nil, ErrUnsupportedAlgorithm
414 }
415
416 key := deriveKey(headers.Alg, keySize)
417 block, err := aes.NewCipher(key)
418 if err != nil {
419 return nil, err
420 }
421
422 return josecipher.KeyUnwrap(block, recipient.encryptedKey)
423 }
424
425 // Sign the given payload
426 func (ctx ecDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) {
427 var expectedBitSize int
428 var hash crypto.Hash
429
430 switch alg {
431 case ES256:
432 expectedBitSize = 256
433 hash = crypto.SHA256
434 case ES384:
435 expectedBitSize = 384
436 hash = crypto.SHA384
437 case ES512:
438 expectedBitSize = 521
439 hash = crypto.SHA512
440 }
441
442 curveBits := ctx.privateKey.Curve.Params().BitSize
443 if expectedBitSize != curveBits {
444 return Signature{}, fmt.Errorf("square/go-jose: expected %d bit key, got %d bits instead", expectedBitSize, curveBits)
445 }
446
447 hasher := hash.New()
448
449 // According to documentation, Write() on hash never fails
450 _, _ = hasher.Write(payload)
451 hashed := hasher.Sum(nil)
452
453 r, s, err := ecdsa.Sign(randReader, ctx.privateKey, hashed)
454 if err != nil {
455 return Signature{}, err
456 }
457
458 keyBytes := curveBits / 8
459 if curveBits%8 > 0 {
460 keyBytes += 1
461 }
462
463 // We serialize the outpus (r and s) into big-endian byte arrays and pad
464 // them with zeros on the left to make sure the sizes work out. Both arrays
465 // must be keyBytes long, and the output must be 2*keyBytes long.
466 rBytes := r.Bytes()
467 rBytesPadded := make([]byte, keyBytes)
468 copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
469
470 sBytes := s.Bytes()
471 sBytesPadded := make([]byte, keyBytes)
472 copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
473
474 out := append(rBytesPadded, sBytesPadded...)
475
476 return Signature{
477 Signature: out,
478 protected: &rawHeader{},
479 }, nil
480 }
481
482 // Verify the given payload
483 func (ctx ecEncrypterVerifier) verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error {
484 var keySize int
485 var hash crypto.Hash
486
487 switch alg {
488 case ES256:
489 keySize = 32
490 hash = crypto.SHA256
491 case ES384:
492 keySize = 48
493 hash = crypto.SHA384
494 case ES512:
495 keySize = 66
496 hash = crypto.SHA512
497 default:
498 return ErrUnsupportedAlgorithm
499 }
500
501 if len(signature) != 2*keySize {
502 return fmt.Errorf("square/go-jose: invalid signature size, have %d bytes, wanted %d", len(signature), 2*keySize)
503 }
504
505 hasher := hash.New()
506
507 // According to documentation, Write() on hash never fails
508 _, _ = hasher.Write(payload)
509 hashed := hasher.Sum(nil)
510
511 r := big.NewInt(0).SetBytes(signature[:keySize])
512 s := big.NewInt(0).SetBytes(signature[keySize:])
513
514 match := ecdsa.Verify(ctx.publicKey, hashed, r, s)
515 if !match {
516 return errors.New("square/go-jose: ecdsa signature failed to verify")
517 }
518
519 return nil
520 }