Debian Codegraph @

lib/Crypto/PublicKey/RSA.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # ===================================================================
3 #
4 # Copyright (c) 2016, Legrandin <[email protected]>
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
10 #
11 # 1. Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # 2. Redistributions in binary form must reproduce the above copyright
14 # notice, this list of conditions and the following disclaimer in
15 # the documentation and/or other materials provided with the
16 # distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
30 # ===================================================================
31
32 __all__ = ['generate', 'construct', 'import_key',
33 'RsaKey', 'oid']
34
35 import binascii
36 import struct
37
38 from Crypto import Random
39 from Crypto.Util.py3compat import tobytes, bord, tostr
40 from Crypto.Util.asn1 import DerSequence, DerNull
41 from Crypto.Util.number import bytes_to_long
42
43 from Crypto.Math.Numbers import Integer
44 from Crypto.Math.Primality import (test_probable_prime,
45 generate_probable_prime, COMPOSITE)
46
47 from Crypto.PublicKey import (_expand_subject_public_key_info,
48 _create_subject_public_key_info,
49 _extract_subject_public_key_info)
50
51
52 class RsaKey(object):
53 r"""Class defining an RSA key, private or public.
54 Do not instantiate directly.
55 Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
56
57 :ivar n: RSA modulus
58 :vartype n: integer
59
60 :ivar e: RSA public exponent
61 :vartype e: integer
62
63 :ivar d: RSA private exponent
64 :vartype d: integer
65
66 :ivar p: First factor of the RSA modulus
67 :vartype p: integer
68
69 :ivar q: Second factor of the RSA modulus
70 :vartype q: integer
71
72 :ivar invp: Chinese remainder component (:math:`p^{-1} \text{mod } q`)
73 :vartype invp: integer
74
75 :ivar invq: Chinese remainder component (:math:`q^{-1} \text{mod } p`)
76 :vartype invq: integer
77
78 :ivar u: Same as ``invp``
79 :vartype u: integer
80 """
81
82 def __init__(self, **kwargs):
83 """Build an RSA key.
84
85 :Keywords:
86 n : integer
87 The modulus.
88 e : integer
89 The public exponent.
90 d : integer
91 The private exponent. Only required for private keys.
92 p : integer
93 The first factor of the modulus. Only required for private keys.
94 q : integer
95 The second factor of the modulus. Only required for private keys.
96 u : integer
97 The CRT coefficient (inverse of p modulo q). Only required for
98 private keys.
99 """
100
101 input_set = set(kwargs.keys())
102 public_set = set(('n', 'e'))
103 private_set = public_set | set(('p', 'q', 'd', 'u'))
104 if input_set not in (private_set, public_set):
105 raise ValueError("Some RSA components are missing")
106 for component, value in kwargs.items():
107 setattr(self, "_" + component, value)
108 if input_set == private_set:
109 self._dp = self._d % (self._p - 1) # = (e⁻¹) mod (p-1)
110 self._dq = self._d % (self._q - 1) # = (e⁻¹) mod (q-1)
111 self._invq = None # will be computed on demand
112
113 @property
114 def n(self):
115 return int(self._n)
116
117 @property
118 def e(self):
119 return int(self._e)
120
121 @property
122 def d(self):
123 if not self.has_private():
124 raise AttributeError("No private exponent available for public keys")
125 return int(self._d)
126
127 @property
128 def p(self):
129 if not self.has_private():
130 raise AttributeError("No CRT component 'p' available for public keys")
131 return int(self._p)
132
133 @property
134 def q(self):
135 if not self.has_private():
136 raise AttributeError("No CRT component 'q' available for public keys")
137 return int(self._q)
138
139 @property
140 def dp(self):
141 if not self.has_private():
142 raise AttributeError("No CRT component 'dp' available for public keys")
143 return int(self._dp)
144
145 @property
146 def dq(self):
147 if not self.has_private():
148 raise AttributeError("No CRT component 'dq' available for public keys")
149 return int(self._dq)
150
151 @property
152 def invq(self):
153 if not self.has_private():
154 raise AttributeError("No CRT component 'invq' available for public keys")
155 if self._invq is None:
156 self._invq = self._q.inverse(self._p)
157 return int(self._invq)
158
159 @property
160 def invp(self):
161 return self.u
162
163 @property
164 def u(self):
165 if not self.has_private():
166 raise AttributeError("No CRT component 'u' available for public keys")
167 return int(self._u)
168
169 def size_in_bits(self):
170 """Size of the RSA modulus in bits"""
171 return self._n.size_in_bits()
172
173 def size_in_bytes(self):
174 """The minimal amount of bytes that can hold the RSA modulus"""
175 return (self._n.size_in_bits() - 1) // 8 + 1
176
177 def _encrypt(self, plaintext):
178 if not 0 <= plaintext < self._n:
179 raise ValueError("Plaintext too large")
180 return int(pow(Integer(plaintext), self._e, self._n))
181
182 def _decrypt_to_bytes(self, ciphertext):
183 if not 0 <= ciphertext < self._n:
184 raise ValueError("Ciphertext too large")
185 if not self.has_private():
186 raise TypeError("This is not a private key")
187
188 # Blinded RSA decryption (to prevent timing attacks):
189 # Step 1: Generate random secret blinding factor r,
190 # such that 0 < r < n-1
191 r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
192 # Step 2: Compute c' = c * r**e mod n
193 cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
194 # Step 3: Compute m' = c'**d mod n (normal RSA decryption)
195 m1 = pow(cp, self._dp, self._p)
196 m2 = pow(cp, self._dq, self._q)
197 h = ((m2 - m1) * self._u) % self._q
198 mp = h * self._p + m1
199 # Step 4: Compute m = m' * (r**(-1)) mod n
200 # then encode into a big endian byte string
201 result = Integer._mult_modulo_bytes(
202 r.inverse(self._n),
203 mp,
204 self._n)
205 return result
206
207 def _decrypt(self, ciphertext):
208 """Legacy private method"""
209
210 return bytes_to_long(self._decrypt_to_bytes(ciphertext))
211
212 def has_private(self):
213 """Whether this is an RSA private key"""
214
215 return hasattr(self, "_d")
216
217 def can_encrypt(self): # legacy
218 return True
219
220 def can_sign(self): # legacy
221 return True
222
223 def public_key(self):
224 """A matching RSA public key.
225
226 Returns:
227 a new :class:`RsaKey` object
228 """
229 return RsaKey(n=self._n, e=self._e)
230
231 def __eq__(self, other):
232 if self.has_private() != other.has_private():
233 return False
234 if self.n != other.n or self.e != other.e:
235 return False
236 if not self.has_private():
237 return True
238 return (self.d == other.d)
239
240 def __ne__(self, other):
241 return not (self == other)
242
243 def __getstate__(self):
244 # RSA key is not pickable
245 from pickle import PicklingError
246 raise PicklingError
247
248 def __repr__(self):
249 if self.has_private():
250 extra = ", d=%d, p=%d, q=%d, u=%d" % (int(self._d), int(self._p),
251 int(self._q), int(self._u))
252 else:
253 extra = ""
254 return "RsaKey(n=%d, e=%d%s)" % (int(self._n), int(self._e), extra)
255
256 def __str__(self):
257 if self.has_private():
258 key_type = "Private"
259 else:
260 key_type = "Public"
261 return "%s RSA key at 0x%X" % (key_type, id(self))
262
263 def export_key(self, format='PEM', passphrase=None, pkcs=1,
264 protection=None, randfunc=None, prot_params=None):
265 """Export this RSA key.
266
267 Keyword Args:
268 format (string):
269 The desired output format:
270
271 - ``'PEM'``. (default) Text output, according to `RFC1421`_/`RFC1423`_.
272 - ``'DER'``. Binary output.
273 - ``'OpenSSH'``. Text output, according to the OpenSSH specification.
274 Only suitable for public keys (not private keys).
275
276 Note that PEM contains a DER structure.
277
278 passphrase (bytes or string):
279 (*Private keys only*) The passphrase to protect the
280 private key.
281
282 pkcs (integer):
283 (*Private keys only*) The standard to use for
284 serializing the key: PKCS#1 or PKCS#8.
285
286 With ``pkcs=1`` (*default*), the private key is encoded with a
287 simple `PKCS#1`_ structure (``RSAPrivateKey``). The key cannot be
288 securely encrypted.
289
290 With ``pkcs=8``, the private key is encoded with a `PKCS#8`_ structure
291 (``PrivateKeyInfo``). PKCS#8 offers the best ways to securely
292 encrypt the key.
293
294 .. note::
295 This parameter is ignored for a public key.
296 For DER and PEM, the output is always an
297 ASN.1 DER ``SubjectPublicKeyInfo`` structure.
298
299 protection (string):
300 (*For private keys only*)
301 The encryption scheme to use for protecting the private key
302 using the passphrase.
303
304 You can only specify a value if ``pkcs=8``.
305 For all possible protection schemes,
306 refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
307 The recommended value is
308 ``'PBKDF2WithHMAC-SHA512AndAES256-CBC'``.
309
310 If ``None`` (default), the behavior depends on :attr:`format`:
311
312 - if ``format='PEM'``, the obsolete PEM encryption scheme is used.
313 It is based on MD5 for key derivation, and 3DES for encryption.
314
315 - if ``format='DER'``, the ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'``
316 scheme is used.
317
318 prot_params (dict):
319 (*For private keys only*)
320
321 The parameters to use to derive the encryption key
322 from the passphrase. ``'protection'`` must be also specified.
323 For all possible values,
324 refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
325 The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2,
326 and ``{'iteration_count':131072}`` for scrypt.
327
328 randfunc (callable):
329 A function that provides random bytes. Only used for PEM encoding.
330 The default is :func:`Crypto.Random.get_random_bytes`.
331
332 Returns:
333 bytes: the encoded key
334
335 Raises:
336 ValueError:when the format is unknown or when you try to encrypt a private
337 key with *DER* format and PKCS#1.
338
339 .. warning::
340 If you don't provide a pass phrase, the private key will be
341 exported in the clear!
342
343 .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
344 .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
345 .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
346 .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
347 """
348
349 if passphrase is not None:
350 passphrase = tobytes(passphrase)
351
352 if randfunc is None:
353 randfunc = Random.get_random_bytes
354
355 if format == 'OpenSSH':
356 e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)]
357 if bord(e_bytes[0]) & 0x80:
358 e_bytes = b'\x00' + e_bytes
359 if bord(n_bytes[0]) & 0x80:
360 n_bytes = b'\x00' + n_bytes
361 keyparts = [b'ssh-rsa', e_bytes, n_bytes]
362 keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
363 return b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1]
364
365 # DER format is always used, even in case of PEM, which simply
366 # encodes it into BASE64.
367 if self.has_private():
368 binary_key = DerSequence([0,
369 self.n,
370 self.e,
371 self.d,
372 self.p,
373 self.q,
374 self.d % (self.p-1),
375 self.d % (self.q-1),
376 Integer(self.q).inverse(self.p)
377 ]).encode()
378 if pkcs == 1:
379 key_type = 'RSA PRIVATE KEY'
380 if format == 'DER' and passphrase:
381 raise ValueError("PKCS#1 private key cannot be encrypted")
382 else: # PKCS#8
383 from Crypto.IO import PKCS8
384
385 if format == 'PEM' and protection is None:
386 key_type = 'PRIVATE KEY'
387 binary_key = PKCS8.wrap(binary_key, oid, None,
388 key_params=DerNull())
389 else:
390 key_type = 'ENCRYPTED PRIVATE KEY'
391 if not protection:
392 if prot_params:
393 raise ValueError("'protection' parameter must be set")
394 protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
395 binary_key = PKCS8.wrap(binary_key, oid,
396 passphrase, protection,
397 prot_params=prot_params,
398 key_params=DerNull())
399 passphrase = None
400 else:
401 key_type = "PUBLIC KEY"
402 binary_key = _create_subject_public_key_info(oid,
403 DerSequence([self.n,
404 self.e]),
405 DerNull()
406 )
407
408 if format == 'DER':
409 return binary_key
410 if format == 'PEM':
411 from Crypto.IO import PEM
412
413 pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc)
414 return tobytes(pem_str)
415
416 raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
417
418 # Backward compatibility
419 def exportKey(self, *args, **kwargs):
420 """:meta private:"""
421 return self.export_key(*args, **kwargs)
422
423 def publickey(self):
424 """:meta private:"""
425 return self.public_key()
426
427 # Methods defined in PyCrypto that we don't support anymore
428 def sign(self, M, K):
429 """:meta private:"""
430 raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
431
432 def verify(self, M, signature):
433 """:meta private:"""
434 raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
435
436 def encrypt(self, plaintext, K):
437 """:meta private:"""
438 raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
439
440 def decrypt(self, ciphertext):
441 """:meta private:"""
442 raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
443
444 def blind(self, M, B):
445 """:meta private:"""
446 raise NotImplementedError
447
448 def unblind(self, M, B):
449 """:meta private:"""
450 raise NotImplementedError
451
452 def size(self):
453 """:meta private:"""
454 raise NotImplementedError
455
456
457 def generate(bits, randfunc=None, e=65537):
458 """Create a new RSA key pair.
459
460 The algorithm closely follows NIST `FIPS 186-4`_ in its
461 sections B.3.1 and B.3.3. The modulus is the product of
462 two non-strong probable primes.
463 Each prime passes a suitable number of Miller-Rabin tests
464 with random bases and a single Lucas test.
465
466 Args:
467 bits (integer):
468 Key length, or size (in bits) of the RSA modulus.
469 It must be at least 1024, but **2048 is recommended.**
470 The FIPS standard only defines 1024, 2048 and 3072.
471 Keyword Args:
472 randfunc (callable):
473 Function that returns random bytes.
474 The default is :func:`Crypto.Random.get_random_bytes`.
475 e (integer):
476 Public RSA exponent. It must be an odd positive integer.
477 It is typically a small number with very few ones in its
478 binary representation.
479 The FIPS standard requires the public exponent to be
480 at least 65537 (the default).
481
482 Returns: an RSA key object (:class:`RsaKey`, with private key).
483
484 .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
485 """
486
487 if bits < 1024:
488 raise ValueError("RSA modulus length must be >= 1024")
489 if e % 2 == 0 or e < 3:
490 raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
491
492 if randfunc is None:
493 randfunc = Random.get_random_bytes
494
495 d = n = Integer(1)
496 e = Integer(e)
497
498 while n.size_in_bits() != bits and d < (1 << (bits // 2)):
499 # Generate the prime factors of n: p and q.
500 # By construciton, their product is always
501 # 2^{bits-1} < p*q < 2^bits.
502 size_q = bits // 2
503 size_p = bits - size_q
504
505 min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt()
506 if size_q != size_p:
507 min_p = (Integer(1) << (2 * size_p - 1)).sqrt()
508
509 def filter_p(candidate):
510 return candidate > min_p and (candidate - 1).gcd(e) == 1
511
512 p = generate_probable_prime(exact_bits=size_p,
513 randfunc=randfunc,
514 prime_filter=filter_p)
515
516 min_distance = Integer(1) << (bits // 2 - 100)
517
518 def filter_q(candidate):
519 return (candidate > min_q and
520 (candidate - 1).gcd(e) == 1 and
521 abs(candidate - p) > min_distance)
522
523 q = generate_probable_prime(exact_bits=size_q,
524 randfunc=randfunc,
525 prime_filter=filter_q)
526
527 n = p * q
528 lcm = (p - 1).lcm(q - 1)
529 d = e.inverse(lcm)
530
531 if p > q:
532 p, q = q, p
533
534 u = p.inverse(q)
535
536 return RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
537
538
539 def construct(rsa_components, consistency_check=True):
540 r"""Construct an RSA key from a tuple of valid RSA components.
541
542 The modulus **n** must be the product of two primes.
543 The public exponent **e** must be odd and larger than 1.
544
545 In case of a private key, the following equations must apply:
546
547 .. math::
548
549 \begin{align}
550 p*q &= n \\
551 e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\
552 p*u &\equiv 1 ( \text{mod } q)
553 \end{align}
554
555 Args:
556 rsa_components (tuple):
557 A tuple of integers, with at least 2 and no
558 more than 6 items. The items come in the following order:
559
560 1. RSA modulus *n*.
561 2. Public exponent *e*.
562 3. Private exponent *d*.
563 Only required if the key is private.
564 4. First factor of *n* (*p*).
565 Optional, but the other factor *q* must also be present.
566 5. Second factor of *n* (*q*). Optional.
567 6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional.
568
569 Keyword Args:
570 consistency_check (boolean):
571 If ``True``, the library will verify that the provided components
572 fulfil the main RSA properties.
573
574 Raises:
575 ValueError: when the key being imported fails the most basic RSA validity checks.
576
577 Returns: An RSA key object (:class:`RsaKey`).
578 """
579
580 class InputComps(object):
581 pass
582
583 input_comps = InputComps()
584 for (comp, value) in zip(('n', 'e', 'd', 'p', 'q', 'u'), rsa_components):
585 setattr(input_comps, comp, Integer(value))
586
587 n = input_comps.n
588 e = input_comps.e
589 if not hasattr(input_comps, 'd'):
590 key = RsaKey(n=n, e=e)
591 else:
592 d = input_comps.d
593 if hasattr(input_comps, 'q'):
594 p = input_comps.p
595 q = input_comps.q
596 else:
597 # Compute factors p and q from the private exponent d.
598 # We assume that n has no more than two factors.
599 # See 8.2.2(i) in Handbook of Applied Cryptography.
600 ktot = d * e - 1
601 # The quantity d*e-1 is a multiple of phi(n), even,
602 # and can be represented as t*2^s.
603 t = ktot
604 while t % 2 == 0:
605 t //= 2
606 # Cycle through all multiplicative inverses in Zn.
607 # The algorithm is non-deterministic, but there is a 50% chance
608 # any candidate a leads to successful factoring.
609 # See "Digitalized Signatures and Public Key Functions as Intractable
610 # as Factorization", M. Rabin, 1979
611 spotted = False
612 a = Integer(2)
613 while not spotted and a < 100:
614 k = Integer(t)
615 # Cycle through all values a^{t*2^i}=a^k
616 while k < ktot:
617 cand = pow(a, k, n)
618 # Check if a^k is a non-trivial root of unity (mod n)
619 if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
620 # We have found a number such that (cand-1)(cand+1)=0 (mod n).
621 # Either of the terms divides n.
622 p = Integer(n).gcd(cand + 1)
623 spotted = True
624 break
625 k *= 2
626 # This value was not any good... let's try another!
627 a += 2
628 if not spotted:
629 raise ValueError("Unable to compute factors p and q from exponent d.")
630 # Found !
631 assert ((n % p) == 0)
632 q = n // p
633
634 if hasattr(input_comps, 'u'):
635 u = input_comps.u
636 else:
637 u = p.inverse(q)
638
639 # Build key object
640 key = RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
641
642 # Verify consistency of the key
643 if consistency_check:
644
645 # Modulus and public exponent must be coprime
646 if e <= 1 or e >= n:
647 raise ValueError("Invalid RSA public exponent")
648 if Integer(n).gcd(e) != 1:
649 raise ValueError("RSA public exponent is not coprime to modulus")
650
651 # For RSA, modulus must be odd
652 if not n & 1:
653 raise ValueError("RSA modulus is not odd")
654
655 if key.has_private():
656 # Modulus and private exponent must be coprime
657 if d <= 1 or d >= n:
658 raise ValueError("Invalid RSA private exponent")
659 if Integer(n).gcd(d) != 1:
660 raise ValueError("RSA private exponent is not coprime to modulus")
661 # Modulus must be product of 2 primes
662 if p * q != n:
663 raise ValueError("RSA factors do not match modulus")
664 if test_probable_prime(p) == COMPOSITE:
665 raise ValueError("RSA factor p is composite")
666 if test_probable_prime(q) == COMPOSITE:
667 raise ValueError("RSA factor q is composite")
668 # See Carmichael theorem
669 phi = (p - 1) * (q - 1)
670 lcm = phi // (p - 1).gcd(q - 1)
671 if (e * d % int(lcm)) != 1:
672 raise ValueError("Invalid RSA condition")
673 if hasattr(key, 'u'):
674 # CRT coefficient
675 if u <= 1 or u >= q:
676 raise ValueError("Invalid RSA component u")
677 if (p * u % q) != 1:
678 raise ValueError("Invalid RSA component u with p")
679
680 return key
681
682
683 def _import_pkcs1_private(encoded, *kwargs):
684 # RSAPrivateKey ::= SEQUENCE {
685 # version Version,
686 # modulus INTEGER, -- n
687 # publicExponent INTEGER, -- e
688 # privateExponent INTEGER, -- d
689 # prime1 INTEGER, -- p
690 # prime2 INTEGER, -- q
691 # exponent1 INTEGER, -- d mod (p-1)
692 # exponent2 INTEGER, -- d mod (q-1)
693 # coefficient INTEGER -- (inverse of q) mod p
694 # }
695 #
696 # Version ::= INTEGER
697 der = DerSequence().decode(encoded, nr_elements=9, only_ints_expected=True)
698 if der[0] != 0:
699 raise ValueError("No PKCS#1 encoding of an RSA private key")
700 return construct(der[1:6] + [Integer(der[4]).inverse(der[5])])
701
702
703 def _import_pkcs1_public(encoded, *kwargs):
704 # RSAPublicKey ::= SEQUENCE {
705 # modulus INTEGER, -- n
706 # publicExponent INTEGER -- e
707 # }
708 der = DerSequence().decode(encoded, nr_elements=2, only_ints_expected=True)
709 return construct(der)
710
711
712 def _import_subjectPublicKeyInfo(encoded, *kwargs):
713
714 algoid, encoded_key, params = _expand_subject_public_key_info(encoded)
715 if algoid != oid or params is not None:
716 raise ValueError("No RSA subjectPublicKeyInfo")
717 return _import_pkcs1_public(encoded_key)
718
719
720 def _import_x509_cert(encoded, *kwargs):
721
722 sp_info = _extract_subject_public_key_info(encoded)
723 return _import_subjectPublicKeyInfo(sp_info)
724
725
726 def _import_pkcs8(encoded, passphrase):
727 from Crypto.IO import PKCS8
728
729 k = PKCS8.unwrap(encoded, passphrase)
730 if k[0] != oid:
731 raise ValueError("No PKCS#8 encoded RSA key")
732 return _import_keyDER(k[1], passphrase)
733
734
735 def _import_keyDER(extern_key, passphrase):
736 """Import an RSA key (public or private half), encoded in DER form."""
737
738 decodings = (_import_pkcs1_private,
739 _import_pkcs1_public,
740 _import_subjectPublicKeyInfo,
741 _import_x509_cert,
742 _import_pkcs8)
743
744 for decoding in decodings:
745 try:
746 return decoding(extern_key, passphrase)
747 except ValueError:
748 pass
749
750 raise ValueError("RSA key format is not supported")
751
752
753 def _import_openssh_private_rsa(data, password):
754
755 from ._openssh import (import_openssh_private_generic,
756 read_bytes, read_string, check_padding)
757
758 ssh_name, decrypted = import_openssh_private_generic(data, password)
759
760 if ssh_name != "ssh-rsa":
761 raise ValueError("This SSH key is not RSA")
762
763 n, decrypted = read_bytes(decrypted)
764 e, decrypted = read_bytes(decrypted)
765 d, decrypted = read_bytes(decrypted)
766 iqmp, decrypted = read_bytes(decrypted)
767 p, decrypted = read_bytes(decrypted)
768 q, decrypted = read_bytes(decrypted)
769
770 _, padded = read_string(decrypted) # Comment
771 check_padding(padded)
772
773 build = [Integer.from_bytes(x) for x in (n, e, d, q, p, iqmp)]
774 return construct(build)
775
776
777 def import_key(extern_key, passphrase=None):
778 """Import an RSA key (public or private).
779
780 Args:
781 extern_key (string or byte string):
782 The RSA key to import.
783
784 The following formats are supported for an RSA **public key**:
785
786 - X.509 certificate (binary or PEM format)
787 - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
788 encoding)
789 - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
790 - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
791
792 The following formats are supported for an RSA **private key**:
793
794 - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
795 - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
796 DER SEQUENCE (binary or PEM encoding)
797 - OpenSSH (text format, introduced in `OpenSSH 6.5`_)
798
799 For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
800
801 passphrase (string or byte string):
802 For private keys only, the pass phrase that encrypts the key.
803
804 Returns: An RSA key object (:class:`RsaKey`).
805
806 Raises:
807 ValueError/IndexError/TypeError:
808 When the given key cannot be parsed (possibly because the pass
809 phrase is wrong).
810
811 .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
812 .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
813 .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
814 .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
815 .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
816 """
817
818 from Crypto.IO import PEM
819
820 extern_key = tobytes(extern_key)
821 if passphrase is not None:
822 passphrase = tobytes(passphrase)
823
824 if extern_key.startswith(b'-----BEGIN OPENSSH PRIVATE KEY'):
825 text_encoded = tostr(extern_key)
826 openssh_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase)
827 result = _import_openssh_private_rsa(openssh_encoded, passphrase)
828 return result
829
830 if extern_key.startswith(b'-----'):
831 # This is probably a PEM encoded key.
832 (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
833 if enc_flag:
834 passphrase = None
835 return _import_keyDER(der, passphrase)
836
837 if extern_key.startswith(b'ssh-rsa '):
838 # This is probably an OpenSSH key
839 keystring = binascii.a2b_base64(extern_key.split(b' ')[1])
840 keyparts = []
841 while len(keystring) > 4:
842 length = struct.unpack(">I", keystring[:4])[0]
843 keyparts.append(keystring[4:4 + length])
844 keystring = keystring[4 + length:]
845 e = Integer.from_bytes(keyparts[1])
846 n = Integer.from_bytes(keyparts[2])
847 return construct([n, e])
848
849 if len(extern_key) > 0 and bord(extern_key[0]) == 0x30:
850 # This is probably a DER encoded key
851 return _import_keyDER(extern_key, passphrase)
852
853 raise ValueError("RSA key format is not supported")
854
855
856 # Backward compatibility
857 importKey = import_key
858
859 #: `Object ID`_ for the RSA encryption algorithm. This OID often indicates
860 #: a generic RSA key, even when such key will be actually used for digital
861 #: signatures.
862 #:
863 #: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html
864 oid = "1.2.840.113549.1.1.1"