| 
									
										
										
										
											2019-12-01 17:05:17 +01:00
										 |  |  | # -*- coding: utf-8 -*- | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | # =================================================================== | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | # | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | # Copyright (c) 2016, Legrandin <helderijs@gmail.com> | 
					
						
							|  |  |  | # All rights reserved. | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | # | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | # Redistribution and use in source and binary forms, with or without | 
					
						
							|  |  |  | # modification, are permitted provided that the following conditions | 
					
						
							|  |  |  | # are met: | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | # | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | # 1. Redistributions of source code must retain the above copyright | 
					
						
							|  |  |  | #    notice, this list of conditions and the following disclaimer. | 
					
						
							|  |  |  | # 2. Redistributions in binary form must reproduce the above copyright | 
					
						
							|  |  |  | #    notice, this list of conditions and the following disclaimer in | 
					
						
							|  |  |  | #    the documentation and/or other materials provided with the | 
					
						
							|  |  |  | #    distribution. | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | # | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | 
					
						
							|  |  |  | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | 
					
						
							|  |  |  | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS | 
					
						
							|  |  |  | # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE | 
					
						
							|  |  |  | # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, | 
					
						
							|  |  |  | # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, | 
					
						
							|  |  |  | # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | 
					
						
							|  |  |  | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | 
					
						
							|  |  |  | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | 
					
						
							|  |  |  | # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN | 
					
						
							|  |  |  | # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | 
					
						
							|  |  |  | # POSSIBILITY OF SUCH DAMAGE. | 
					
						
							| 
									
										
										
										
											2009-02-28 13:24:04 -05:00
										 |  |  | # =================================================================== | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | __all__ = ['generate', 'construct', 'import_key', | 
					
						
							|  |  |  |            'RsaKey', 'oid'] | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2010-01-21 20:14:10 +01:00
										 |  |  | import binascii | 
					
						
							| 
									
										
										
										
											2011-09-21 00:01:36 +02:00
										 |  |  | import struct | 
					
						
							| 
									
										
										
										
											2009-12-27 17:26:59 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-06-11 15:46:22 +02:00
										 |  |  | from Crypto import Random | 
					
						
							| 
									
										
										
										
											2018-11-04 11:31:40 +01:00
										 |  |  | from Crypto.Util.py3compat import tobytes, bord, tostr | 
					
						
							| 
									
										
										
										
											2022-04-15 00:15:48 +02:00
										 |  |  | from Crypto.Util.asn1 import DerSequence, DerNull | 
					
						
							| 
									
										
										
										
											2011-01-16 21:44:10 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | from Crypto.Math.Numbers import Integer | 
					
						
							|  |  |  | from Crypto.Math.Primality import (test_probable_prime, | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                                    generate_probable_prime, COMPOSITE) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  | from Crypto.PublicKey import (_expand_subject_public_key_info, | 
					
						
							| 
									
										
										
										
											2016-01-27 08:33:55 +01:00
										 |  |  |                               _create_subject_public_key_info, | 
					
						
							|  |  |  |                               _extract_subject_public_key_info) | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 21:09:36 +01:00
										 |  |  | class RsaKey(object): | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |     r"""Class defining an actual RSA key.
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Do not instantiate directly. | 
					
						
							|  |  |  |     Use :func:`generate`, :func:`construct` or :func:`import_key` instead. | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     :ivar n: RSA modulus | 
					
						
							|  |  |  |     :vartype n: integer | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     :ivar e: RSA public exponent | 
					
						
							|  |  |  |     :vartype e: integer | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     :ivar d: RSA private exponent | 
					
						
							|  |  |  |     :vartype d: integer | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  | 
 | 
					
						
							|  |  |  |     :ivar p: First factor of the RSA modulus | 
					
						
							|  |  |  |     :vartype p: integer | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     :ivar q: Second factor of the RSA modulus | 
					
						
							|  |  |  |     :vartype q: integer | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     :ivar u: Chinese remainder component (:math:`p^{-1} \text{mod } q`) | 
					
						
							| 
									
										
										
										
											2021-04-10 22:40:07 +09:00
										 |  |  |     :vartype u: integer | 
					
						
							| 
									
										
										
										
											2020-11-15 21:41:51 +01:00
										 |  |  | 
 | 
					
						
							|  |  |  |     :undocumented: exportKey, publickey | 
					
						
							| 
									
										
										
										
											2012-04-10 21:26:33 +02:00
										 |  |  |     """
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | 
 | 
					
						
							|  |  |  |     def __init__(self, **kwargs): | 
					
						
							|  |  |  |         """Build an RSA key.
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         :Keywords: | 
					
						
							|  |  |  |           n : integer | 
					
						
							|  |  |  |             The modulus. | 
					
						
							|  |  |  |           e : integer | 
					
						
							|  |  |  |             The public exponent. | 
					
						
							|  |  |  |           d : integer | 
					
						
							|  |  |  |             The private exponent. Only required for private keys. | 
					
						
							|  |  |  |           p : integer | 
					
						
							|  |  |  |             The first factor of the modulus. Only required for private keys. | 
					
						
							|  |  |  |           q : integer | 
					
						
							|  |  |  |             The second factor of the modulus. Only required for private keys. | 
					
						
							|  |  |  |           u : integer | 
					
						
							|  |  |  |             The CRT coefficient (inverse of p modulo q). Only required for | 
					
						
							| 
									
										
										
										
											2019-06-07 17:43:55 +12:00
										 |  |  |             private keys. | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         """
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         input_set = set(kwargs.keys()) | 
					
						
							|  |  |  |         public_set = set(('n', 'e')) | 
					
						
							|  |  |  |         private_set = public_set | set(('p', 'q', 'd', 'u')) | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  |         if input_set not in (private_set, public_set): | 
					
						
							|  |  |  |             raise ValueError("Some RSA components are missing") | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         for component, value in kwargs.items(): | 
					
						
							|  |  |  |             setattr(self, "_" + component, value) | 
					
						
							| 
									
										
										
										
											2019-12-01 17:05:17 +01:00
										 |  |  |         if input_set == private_set: | 
					
						
							|  |  |  |             self._dp = self._d % (self._p - 1)  # = (e⁻¹) mod (p-1) | 
					
						
							|  |  |  |             self._dq = self._d % (self._q - 1)  # = (e⁻¹) mod (q-1) | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | 
 | 
					
						
							|  |  |  |     @property | 
					
						
							|  |  |  |     def n(self): | 
					
						
							|  |  |  |         return int(self._n) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     @property | 
					
						
							|  |  |  |     def e(self): | 
					
						
							|  |  |  |         return int(self._e) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     @property | 
					
						
							|  |  |  |     def d(self): | 
					
						
							|  |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             raise AttributeError("No private exponent available for public keys") | 
					
						
							|  |  |  |         return int(self._d) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |     @property | 
					
						
							|  |  |  |     def p(self): | 
					
						
							|  |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             raise AttributeError("No CRT component 'p' available for public keys") | 
					
						
							|  |  |  |         return int(self._p) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     @property | 
					
						
							|  |  |  |     def q(self): | 
					
						
							|  |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             raise AttributeError("No CRT component 'q' available for public keys") | 
					
						
							|  |  |  |         return int(self._q) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     @property | 
					
						
							|  |  |  |     def u(self): | 
					
						
							|  |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             raise AttributeError("No CRT component 'u' available for public keys") | 
					
						
							|  |  |  |         return int(self._u) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:53:26 +01:00
										 |  |  |     def size_in_bits(self): | 
					
						
							|  |  |  |         """Size of the RSA modulus in bits""" | 
					
						
							|  |  |  |         return self._n.size_in_bits() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def size_in_bytes(self): | 
					
						
							|  |  |  |         """The minimal amount of bytes that can hold the RSA modulus""" | 
					
						
							|  |  |  |         return (self._n.size_in_bits() - 1) // 8 + 1 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-06-16 21:42:39 +02:00
										 |  |  |     def _encrypt(self, plaintext): | 
					
						
							| 
									
										
										
										
											2019-12-15 00:30:31 +01:00
										 |  |  |         if not 0 <= plaintext < self._n: | 
					
						
							| 
									
										
										
										
											2014-05-07 12:20:46 +02:00
										 |  |  |             raise ValueError("Plaintext too large") | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         return int(pow(Integer(plaintext), self._e, self._n)) | 
					
						
							| 
									
										
										
										
											2011-02-21 21:11:21 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-06-16 21:42:39 +02:00
										 |  |  |     def _decrypt(self, ciphertext): | 
					
						
							| 
									
										
										
										
											2019-12-15 00:30:31 +01:00
										 |  |  |         if not 0 <= ciphertext < self._n: | 
					
						
							| 
									
										
										
										
											2014-05-07 12:20:46 +02:00
										 |  |  |             raise ValueError("Ciphertext too large") | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             raise TypeError("This is not a private key") | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2011-02-21 21:11:21 -05:00
										 |  |  |         # Blinded RSA decryption (to prevent timing attacks): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         # Step 1: Generate random secret blinding factor r, | 
					
						
							|  |  |  |         # such that 0 < r < n-1 | 
					
						
							|  |  |  |         r = Integer.random_range(min_inclusive=1, max_exclusive=self._n) | 
					
						
							| 
									
										
										
										
											2011-02-21 21:11:21 -05:00
										 |  |  |         # Step 2: Compute c' = c * r**e mod n | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n | 
					
						
							| 
									
										
										
										
											2019-12-01 17:05:17 +01:00
										 |  |  |         # Step 3: Compute m' = c'**d mod n       (normal RSA decryption) | 
					
						
							|  |  |  |         m1 = pow(cp, self._dp, self._p) | 
					
						
							|  |  |  |         m2 = pow(cp, self._dq, self._q) | 
					
						
							| 
									
										
										
										
											2019-11-18 16:07:07 +01:00
										 |  |  |         h = ((m2 - m1) * self._u) % self._q | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         mp = h * self._p + m1 | 
					
						
							| 
									
										
										
										
											2022-04-16 12:23:16 +02:00
										 |  |  |         # Step 4: Compute m = m*(r**(-1)) mod n | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         result = (r.inverse(self._n) * mp) % self._n | 
					
						
							| 
									
										
										
										
											2020-01-26 22:39:02 -06:00
										 |  |  |         # Verify no faults occurred | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if ciphertext != pow(result, self._e, self._n): | 
					
						
							| 
									
										
										
										
											2015-09-23 08:58:09 +02:00
										 |  |  |             raise ValueError("Fault detected in RSA decryption") | 
					
						
							|  |  |  |         return result | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     def has_private(self): | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |         """Whether this is an RSA private key""" | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         return hasattr(self, "_d") | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |     def can_encrypt(self):  # legacy | 
					
						
							| 
									
										
										
										
											2016-02-04 21:58:53 +01:00
										 |  |  |         return True | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |     def can_sign(self):     # legacy | 
					
						
							| 
									
										
										
										
											2016-02-04 21:58:53 +01:00
										 |  |  |         return True | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2020-11-15 21:41:51 +01:00
										 |  |  |     def public_key(self): | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |         """A matching RSA public key.
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         Returns: | 
					
						
							|  |  |  |             a new :class:`RsaKey` object | 
					
						
							|  |  |  |         """
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         return RsaKey(n=self._n, e=self._e) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-06-16 21:42:39 +02:00
										 |  |  |     def __eq__(self, other): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if self.has_private() != other.has_private(): | 
					
						
							|  |  |  |             return False | 
					
						
							|  |  |  |         if self.n != other.n or self.e != other.e: | 
					
						
							|  |  |  |             return False | 
					
						
							|  |  |  |         if not self.has_private(): | 
					
						
							|  |  |  |             return True | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |         return (self.d == other.d) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2014-06-16 21:42:39 +02:00
										 |  |  |     def __ne__(self, other): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         return not (self == other) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     def __getstate__(self): | 
					
						
							| 
									
										
										
										
											2014-06-16 21:42:39 +02:00
										 |  |  |         # RSA key is not pickable | 
					
						
							|  |  |  |         from pickle import PicklingError | 
					
						
							|  |  |  |         raise PicklingError | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     def __repr__(self): | 
					
						
							|  |  |  |         if self.has_private(): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             extra = ", d=%d, p=%d, q=%d, u=%d" % (int(self._d), int(self._p), | 
					
						
							|  |  |  |                                                   int(self._q), int(self._u)) | 
					
						
							|  |  |  |         else: | 
					
						
							|  |  |  |             extra = "" | 
					
						
							|  |  |  |         return "RsaKey(n=%d, e=%d%s)" % (int(self._n), int(self._e), extra) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |     def __str__(self): | 
					
						
							|  |  |  |         if self.has_private(): | 
					
						
							|  |  |  |             key_type = "Private" | 
					
						
							|  |  |  |         else: | 
					
						
							|  |  |  |             key_type = "Public" | 
					
						
							|  |  |  |         return "%s RSA key at 0x%X" % (key_type, id(self)) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2018-03-25 21:57:43 +02:00
										 |  |  |     def export_key(self, format='PEM', passphrase=None, pkcs=1, | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                    protection=None, randfunc=None): | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  |         """Export this RSA key.
 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |         Args: | 
					
						
							|  |  |  |           format (string): | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             The format to use for wrapping the key: | 
					
						
							| 
									
										
										
										
											2011-01-16 22:05:54 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             - *'DER'*. Binary encoding. | 
					
						
							| 
									
										
										
										
											2011-10-10 08:11:31 +02:00
										 |  |  |             - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. | 
					
						
							|  |  |  |               Only suitable for public keys (not private keys). | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |           passphrase (string): | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             (*For private keys only*) The pass phrase used for protecting the output. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |           pkcs (integer): | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             (*For private keys only*) The ASN.1 structure to use for | 
					
						
							|  |  |  |             serializing the key. Note that even in case of PEM | 
					
						
							|  |  |  |             encoding, there is an inner ASN.1 DER structure. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             With ``pkcs=1`` (*default*), the private key is encoded in a | 
					
						
							|  |  |  |             simple `PKCS#1`_ structure (``RSAPrivateKey``). | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |             With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure | 
					
						
							|  |  |  |             (``PrivateKeyInfo``). | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |             .. note:: | 
					
						
							|  |  |  |                 This parameter is ignored for a public key. | 
					
						
							|  |  |  |                 For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo`` | 
					
						
							|  |  |  |                 structure is always used. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |           protection (string): | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             (*For private keys only*) | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             The encryption scheme to use for protecting the private key. | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             If ``None`` (default), the behavior depends on :attr:`format`: | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC* | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |               scheme is used. The following operations are performed: | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |                 1. A 16 byte Triple DES key is derived from the passphrase | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |                    using :func:`Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt, | 
					
						
							|  |  |  |                    and 1 000 iterations of :mod:`Crypto.Hash.HMAC`. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |                 2. The private key is encrypted using CBC. | 
					
						
							|  |  |  |                 3. The encrypted key is encoded according to PKCS#8. | 
					
						
							| 
									
										
										
										
											2011-10-03 23:33:11 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             - For *'PEM'*, the obsolete PEM encryption scheme is used. | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |               It is based on MD5 for key derivation, and Triple DES for encryption. | 
					
						
							| 
									
										
										
										
											2012-05-18 15:26:58 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             Specifying a value for :attr:`protection` is only meaningful for PKCS#8 | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             (that is, ``pkcs=8``) and only if a pass phrase is present too. | 
					
						
							| 
									
										
										
										
											2012-05-18 15:26:58 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             The supported schemes for PKCS#8 are listed in the | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             :mod:`Crypto.IO.PKCS8` module (see :attr:`wrap_algo` parameter). | 
					
						
							| 
									
										
										
										
											2011-10-10 08:11:31 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |           randfunc (callable): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             A function that provides random bytes. Only used for PEM encoding. | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |             The default is :func:`Crypto.Random.get_random_bytes`. | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  |         Returns: | 
					
						
							|  |  |  |           byte string: the encoded key | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         Raises: | 
					
						
							|  |  |  |           ValueError:when the format is unknown or when you try to encrypt a private | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             key with *DER* format and PKCS#1. | 
					
						
							| 
									
										
										
										
											2017-08-14 23:41:07 +02:00
										 |  |  | 
 | 
					
						
							|  |  |  |         .. warning:: | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             If you don't provide a pass phrase, the private key will be | 
					
						
							|  |  |  |             exported in the clear! | 
					
						
							| 
									
										
										
										
											2012-04-12 23:16:52 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2012-05-18 15:26:58 +02:00
										 |  |  |         .. _RFC1421:    http://www.ietf.org/rfc/rfc1421.txt | 
					
						
							|  |  |  |         .. _RFC1423:    http://www.ietf.org/rfc/rfc1423.txt | 
					
						
							|  |  |  |         .. _`PKCS#1`:   http://www.ietf.org/rfc/rfc3447.txt | 
					
						
							|  |  |  |         .. _`PKCS#8`:   http://www.ietf.org/rfc/rfc5208.txt | 
					
						
							| 
									
										
										
										
											2011-01-16 22:05:54 +01:00
										 |  |  |         """
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2011-10-18 23:20:26 +02:00
										 |  |  |         if passphrase is not None: | 
					
						
							|  |  |  |             passphrase = tobytes(passphrase) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |         if randfunc is None: | 
					
						
							|  |  |  |             randfunc = Random.get_random_bytes | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if format == 'OpenSSH': | 
					
						
							|  |  |  |             e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)] | 
					
						
							|  |  |  |             if bord(e_bytes[0]) & 0x80: | 
					
						
							| 
									
										
										
										
											2018-11-04 11:31:40 +01:00
										 |  |  |                 e_bytes = b'\x00' + e_bytes | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             if bord(n_bytes[0]) & 0x80: | 
					
						
							| 
									
										
										
										
											2018-11-04 11:31:40 +01:00
										 |  |  |                 n_bytes = b'\x00' + n_bytes | 
					
						
							|  |  |  |             keyparts = [b'ssh-rsa', e_bytes, n_bytes] | 
					
						
							|  |  |  |             keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts]) | 
					
						
							|  |  |  |             return b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1] | 
					
						
							| 
									
										
										
										
											2011-09-21 20:54:17 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2011-10-10 08:11:31 +02:00
										 |  |  |         # DER format is always used, even in case of PEM, which simply | 
					
						
							|  |  |  |         # encodes it into BASE64. | 
					
						
							| 
									
										
										
										
											2011-01-16 22:05:54 +01:00
										 |  |  |         if self.has_private(): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             binary_key = DerSequence([0, | 
					
						
							|  |  |  |                                       self.n, | 
					
						
							|  |  |  |                                       self.e, | 
					
						
							|  |  |  |                                       self.d, | 
					
						
							|  |  |  |                                       self.p, | 
					
						
							|  |  |  |                                       self.q, | 
					
						
							|  |  |  |                                       self.d % (self.p-1), | 
					
						
							|  |  |  |                                       self.d % (self.q-1), | 
					
						
							|  |  |  |                                       Integer(self.q).inverse(self.p) | 
					
						
							|  |  |  |                                       ]).encode() | 
					
						
							|  |  |  |             if pkcs == 1: | 
					
						
							|  |  |  |                 key_type = 'RSA PRIVATE KEY' | 
					
						
							|  |  |  |                 if format == 'DER' and passphrase: | 
					
						
							|  |  |  |                     raise ValueError("PKCS#1 private key cannot be encrypted") | 
					
						
							|  |  |  |             else:  # PKCS#8 | 
					
						
							| 
									
										
										
										
											2019-11-01 23:39:04 +01:00
										 |  |  |                 from Crypto.IO import PKCS8 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                 if format == 'PEM' and protection is None: | 
					
						
							|  |  |  |                     key_type = 'PRIVATE KEY' | 
					
						
							| 
									
										
										
										
											2022-04-15 00:15:48 +02:00
										 |  |  |                     binary_key = PKCS8.wrap(binary_key, oid, None, | 
					
						
							|  |  |  |                                             key_params=DerNull()) | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                 else: | 
					
						
							|  |  |  |                     key_type = 'ENCRYPTED PRIVATE KEY' | 
					
						
							|  |  |  |                     if not protection: | 
					
						
							|  |  |  |                         protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' | 
					
						
							|  |  |  |                     binary_key = PKCS8.wrap(binary_key, oid, | 
					
						
							| 
									
										
										
										
											2022-04-15 00:15:48 +02:00
										 |  |  |                                             passphrase, protection, | 
					
						
							|  |  |  |                                             key_params=DerNull()) | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                     passphrase = None | 
					
						
							| 
									
										
										
										
											2011-01-16 22:05:54 +01:00
										 |  |  |         else: | 
					
						
							| 
									
										
										
										
											2017-08-26 12:04:19 +02:00
										 |  |  |             key_type = "PUBLIC KEY" | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             binary_key = _create_subject_public_key_info(oid, | 
					
						
							|  |  |  |                                                          DerSequence([self.n, | 
					
						
							| 
									
										
										
										
											2022-04-15 00:15:48 +02:00
										 |  |  |                                                                       self.e]), | 
					
						
							|  |  |  |                                                          DerNull() | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |                                                          ) | 
					
						
							| 
									
										
										
										
											2016-01-27 08:33:55 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if format == 'DER': | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             return binary_key | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if format == 'PEM': | 
					
						
							| 
									
										
										
										
											2019-11-01 23:39:04 +01:00
										 |  |  |             from Crypto.IO import PEM | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc) | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  |             return tobytes(pem_str) | 
					
						
							| 
									
										
										
										
											2009-12-27 17:26:59 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format) | 
					
						
							| 
									
										
										
										
											2016-02-04 21:38:17 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2018-03-25 21:57:43 +02:00
										 |  |  |     # Backward compatibility | 
					
						
							|  |  |  |     exportKey = export_key | 
					
						
							| 
									
										
										
										
											2020-11-15 21:41:51 +01:00
										 |  |  |     publickey = public_key | 
					
						
							| 
									
										
										
										
											2018-03-25 21:57:43 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-04 21:58:53 +01:00
										 |  |  |     # Methods defined in PyCrypto that we don't support anymore | 
					
						
							|  |  |  |     def sign(self, M, K): | 
					
						
							|  |  |  |         raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead") | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def verify(self, M, signature): | 
					
						
							|  |  |  |         raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead") | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def encrypt(self, plaintext, K): | 
					
						
							|  |  |  |         raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead") | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def decrypt(self, ciphertext): | 
					
						
							|  |  |  |         raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead") | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def blind(self, M, B): | 
					
						
							|  |  |  |         raise NotImplementedError | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     def unblind(self, M, B): | 
					
						
							|  |  |  |         raise NotImplementedError | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2018-10-15 21:58:33 +02:00
										 |  |  |     def size(self): | 
					
						
							| 
									
										
										
										
											2016-02-04 21:58:53 +01:00
										 |  |  |         raise NotImplementedError | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | def generate(bits, randfunc=None, e=65537): | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     """Create a new RSA key pair.
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     The algorithm closely follows NIST `FIPS 186-4`_ in its | 
					
						
							|  |  |  |     sections B.3.1 and B.3.3. The modulus is the product of | 
					
						
							|  |  |  |     two non-strong probable primes. | 
					
						
							|  |  |  |     Each prime passes a suitable number of Miller-Rabin tests | 
					
						
							|  |  |  |     with random bases and a single Lucas test. | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Args: | 
					
						
							|  |  |  |       bits (integer): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         Key length, or size (in bits) of the RSA modulus. | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |         It must be at least 1024, but **2048 is recommended.** | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         The FIPS standard only defines 1024, 2048 and 3072. | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |       randfunc (callable): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         Function that returns random bytes. | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |         The default is :func:`Crypto.Random.get_random_bytes`. | 
					
						
							|  |  |  |       e (integer): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         Public RSA exponent. It must be an odd positive integer. | 
					
						
							|  |  |  |         It is typically a small number with very few ones in its | 
					
						
							|  |  |  |         binary representation. | 
					
						
							|  |  |  |         The FIPS standard requires the public exponent to be | 
					
						
							|  |  |  |         at least 65537 (the default). | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Returns: an RSA key object (:class:`RsaKey`, with private key). | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  |     """
 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     if bits < 1024: | 
					
						
							|  |  |  |         raise ValueError("RSA modulus length must be >= 1024") | 
					
						
							|  |  |  |     if e % 2 == 0 or e < 3: | 
					
						
							|  |  |  |         raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.") | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     if randfunc is None: | 
					
						
							|  |  |  |         randfunc = Random.get_random_bytes | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     d = n = Integer(1) | 
					
						
							|  |  |  |     e = Integer(e) | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     while n.size_in_bits() != bits and d < (1 << (bits // 2)): | 
					
						
							|  |  |  |         # Generate the prime factors of n: p and q. | 
					
						
							|  |  |  |         # By construciton, their product is always | 
					
						
							|  |  |  |         # 2^{bits-1} < p*q < 2^bits. | 
					
						
							|  |  |  |         size_q = bits // 2 | 
					
						
							|  |  |  |         size_p = bits - size_q | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt() | 
					
						
							|  |  |  |         if size_q != size_p: | 
					
						
							|  |  |  |             min_p = (Integer(1) << (2 * size_p - 1)).sqrt() | 
					
						
							| 
									
										
										
										
											2015-02-25 07:35:45 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         def filter_p(candidate): | 
					
						
							|  |  |  |             return candidate > min_p and (candidate - 1).gcd(e) == 1 | 
					
						
							| 
									
										
										
										
											2015-02-25 07:35:45 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         p = generate_probable_prime(exact_bits=size_p, | 
					
						
							|  |  |  |                                     randfunc=randfunc, | 
					
						
							|  |  |  |                                     prime_filter=filter_p) | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         min_distance = Integer(1) << (bits // 2 - 100) | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         def filter_q(candidate): | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             return (candidate > min_q and | 
					
						
							|  |  |  |                     (candidate - 1).gcd(e) == 1 and | 
					
						
							|  |  |  |                     abs(candidate - p) > min_distance) | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         q = generate_probable_prime(exact_bits=size_q, | 
					
						
							|  |  |  |                                     randfunc=randfunc, | 
					
						
							|  |  |  |                                     prime_filter=filter_q) | 
					
						
							| 
									
										
										
										
											2015-02-27 21:57:21 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         n = p * q | 
					
						
							|  |  |  |         lcm = (p - 1).lcm(q - 1) | 
					
						
							|  |  |  |         d = e.inverse(lcm) | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     if p > q: | 
					
						
							|  |  |  |         p, q = q, p | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     u = p.inverse(q) | 
					
						
							| 
									
										
										
										
											2014-12-05 08:12:51 -05:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |     return RsaKey(n=n, e=e, d=d, p=p, q=q, u=u) | 
					
						
							| 
									
										
										
										
											2008-09-18 21:42:28 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  | def construct(rsa_components, consistency_check=True): | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     r"""Construct an RSA key from a tuple of valid RSA components.
 | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     The modulus **n** must be the product of two primes. | 
					
						
							|  |  |  |     The public exponent **e** must be odd and larger than 1. | 
					
						
							| 
									
										
										
										
											2011-01-21 18:54:53 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     In case of a private key, the following equations must apply: | 
					
						
							| 
									
										
										
										
											2013-06-17 23:25:21 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     .. math:: | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         \begin{align} | 
					
						
							|  |  |  |         p*q &= n \\ | 
					
						
							|  |  |  |         e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\ | 
					
						
							|  |  |  |         p*u &\equiv 1 ( \text{mod } q) | 
					
						
							|  |  |  |         \end{align} | 
					
						
							| 
									
										
										
										
											2013-06-17 23:25:21 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Args: | 
					
						
							|  |  |  |         rsa_components (tuple): | 
					
						
							|  |  |  |             A tuple of integers, with at least 2 and no | 
					
						
							|  |  |  |             more than 6 items. The items come in the following order: | 
					
						
							| 
									
										
										
										
											2011-10-10 08:11:31 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |             1. RSA modulus *n*. | 
					
						
							|  |  |  |             2. Public exponent *e*. | 
					
						
							|  |  |  |             3. Private exponent *d*. | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |                Only required if the key is private. | 
					
						
							|  |  |  |             4. First factor of *n* (*p*). | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |                Optional, but the other factor *q* must also be present. | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             5. Second factor of *n* (*q*). Optional. | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |             6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional. | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |         consistency_check (boolean): | 
					
						
							|  |  |  |             If ``True``, the library will verify that the provided components | 
					
						
							|  |  |  |             fulfil the main RSA properties. | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     Raises: | 
					
						
							|  |  |  |         ValueError: when the key being imported fails the most basic RSA validity checks. | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     Returns: An RSA key object (:class:`RsaKey`). | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     """
 | 
					
						
							| 
									
										
										
										
											2011-10-18 23:20:26 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |     class InputComps(object): | 
					
						
							|  |  |  |         pass | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     input_comps = InputComps() | 
					
						
							|  |  |  |     for (comp, value) in zip(('n', 'e', 'd', 'p', 'q', 'u'), rsa_components): | 
					
						
							|  |  |  |         setattr(input_comps, comp, Integer(value)) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     n = input_comps.n | 
					
						
							|  |  |  |     e = input_comps.e | 
					
						
							|  |  |  |     if not hasattr(input_comps, 'd'): | 
					
						
							|  |  |  |         key = RsaKey(n=n, e=e) | 
					
						
							|  |  |  |     else: | 
					
						
							|  |  |  |         d = input_comps.d | 
					
						
							|  |  |  |         if hasattr(input_comps, 'q'): | 
					
						
							|  |  |  |             p = input_comps.p | 
					
						
							|  |  |  |             q = input_comps.q | 
					
						
							|  |  |  |         else: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             # Compute factors p and q from the private exponent d. | 
					
						
							|  |  |  |             # We assume that n has no more than two factors. | 
					
						
							|  |  |  |             # See 8.2.2(i) in Handbook of Applied Cryptography. | 
					
						
							|  |  |  |             ktot = d * e - 1 | 
					
						
							|  |  |  |             # The quantity d*e-1 is a multiple of phi(n), even, | 
					
						
							|  |  |  |             # and can be represented as t*2^s. | 
					
						
							|  |  |  |             t = ktot | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |             while t % 2 == 0: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |                 t //= 2 | 
					
						
							|  |  |  |             # Cycle through all multiplicative inverses in Zn. | 
					
						
							|  |  |  |             # The algorithm is non-deterministic, but there is a 50% chance | 
					
						
							|  |  |  |             # any candidate a leads to successful factoring. | 
					
						
							|  |  |  |             # See "Digitalized Signatures and Public Key Functions as Intractable | 
					
						
							|  |  |  |             # as Factorization", M. Rabin, 1979 | 
					
						
							|  |  |  |             spotted = False | 
					
						
							|  |  |  |             a = Integer(2) | 
					
						
							|  |  |  |             while not spotted and a < 100: | 
					
						
							|  |  |  |                 k = Integer(t) | 
					
						
							|  |  |  |                 # Cycle through all values a^{t*2^i}=a^k | 
					
						
							|  |  |  |                 while k < ktot: | 
					
						
							|  |  |  |                     cand = pow(a, k, n) | 
					
						
							|  |  |  |                     # Check if a^k is a non-trivial root of unity (mod n) | 
					
						
							|  |  |  |                     if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: | 
					
						
							|  |  |  |                         # We have found a number such that (cand-1)(cand+1)=0 (mod n). | 
					
						
							|  |  |  |                         # Either of the terms divides n. | 
					
						
							|  |  |  |                         p = Integer(n).gcd(cand + 1) | 
					
						
							|  |  |  |                         spotted = True | 
					
						
							|  |  |  |                         break | 
					
						
							|  |  |  |                     k *= 2 | 
					
						
							|  |  |  |                 # This value was not any good... let's try another! | 
					
						
							|  |  |  |                 a += 2 | 
					
						
							|  |  |  |             if not spotted: | 
					
						
							|  |  |  |                 raise ValueError("Unable to compute factors p and q from exponent d.") | 
					
						
							|  |  |  |             # Found ! | 
					
						
							|  |  |  |             assert ((n % p) == 0) | 
					
						
							|  |  |  |             q = n // p | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         if hasattr(input_comps, 'u'): | 
					
						
							|  |  |  |             u = input_comps.u | 
					
						
							|  |  |  |         else: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             u = p.inverse(q) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |         # Build key object | 
					
						
							|  |  |  |         key = RsaKey(n=n, e=e, d=d, p=p, q=q, u=u) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |     # Verify consistency of the key | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     if consistency_check: | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         # Modulus and public exponent must be coprime | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |         if e <= 1 or e >= n: | 
					
						
							|  |  |  |             raise ValueError("Invalid RSA public exponent") | 
					
						
							|  |  |  |         if Integer(n).gcd(e) != 1: | 
					
						
							|  |  |  |             raise ValueError("RSA public exponent is not coprime to modulus") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |         # For RSA, modulus must be odd | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |         if not n & 1: | 
					
						
							|  |  |  |             raise ValueError("RSA modulus is not odd") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |         if key.has_private(): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             # Modulus and private exponent must be coprime | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |             if d <= 1 or d >= n: | 
					
						
							|  |  |  |                 raise ValueError("Invalid RSA private exponent") | 
					
						
							|  |  |  |             if Integer(n).gcd(d) != 1: | 
					
						
							|  |  |  |                 raise ValueError("RSA private exponent is not coprime to modulus") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             # Modulus must be product of 2 primes | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |             if p * q != n: | 
					
						
							|  |  |  |                 raise ValueError("RSA factors do not match modulus") | 
					
						
							|  |  |  |             if test_probable_prime(p) == COMPOSITE: | 
					
						
							|  |  |  |                 raise ValueError("RSA factor p is composite") | 
					
						
							|  |  |  |             if test_probable_prime(q) == COMPOSITE: | 
					
						
							|  |  |  |                 raise ValueError("RSA factor q is composite") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             # See Carmichael theorem | 
					
						
							|  |  |  |             phi = (p - 1) * (q - 1) | 
					
						
							|  |  |  |             lcm = phi // (p - 1).gcd(q - 1) | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |             if (e * d % int(lcm)) != 1: | 
					
						
							|  |  |  |                 raise ValueError("Invalid RSA condition") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |             if hasattr(key, 'u'): | 
					
						
							|  |  |  |                 # CRT coefficient | 
					
						
							| 
									
										
										
										
											2017-08-26 22:24:12 +02:00
										 |  |  |                 if u <= 1 or u >= q: | 
					
						
							|  |  |  |                     raise ValueError("Invalid RSA component u") | 
					
						
							|  |  |  |                 if (p * u % q) != 1: | 
					
						
							|  |  |  |                     raise ValueError("Invalid RSA component u with p") | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     return key | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  | def _import_pkcs1_private(encoded, *kwargs): | 
					
						
							|  |  |  |     # RSAPrivateKey ::= SEQUENCE { | 
					
						
							|  |  |  |     #           version Version, | 
					
						
							|  |  |  |     #           modulus INTEGER, -- n | 
					
						
							|  |  |  |     #           publicExponent INTEGER, -- e | 
					
						
							|  |  |  |     #           privateExponent INTEGER, -- d | 
					
						
							|  |  |  |     #           prime1 INTEGER, -- p | 
					
						
							|  |  |  |     #           prime2 INTEGER, -- q | 
					
						
							|  |  |  |     #           exponent1 INTEGER, -- d mod (p-1) | 
					
						
							|  |  |  |     #           exponent2 INTEGER, -- d mod (q-1) | 
					
						
							|  |  |  |     #           coefficient INTEGER -- (inverse of q) mod p | 
					
						
							|  |  |  |     # } | 
					
						
							|  |  |  |     # | 
					
						
							|  |  |  |     # Version ::= INTEGER | 
					
						
							|  |  |  |     der = DerSequence().decode(encoded, nr_elements=9, only_ints_expected=True) | 
					
						
							|  |  |  |     if der[0] != 0: | 
					
						
							|  |  |  |         raise ValueError("No PKCS#1 encoding of an RSA private key") | 
					
						
							|  |  |  |     return construct(der[1:6] + [Integer(der[4]).inverse(der[5])]) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | def _import_pkcs1_public(encoded, *kwargs): | 
					
						
							|  |  |  |     # RSAPublicKey ::= SEQUENCE { | 
					
						
							|  |  |  |     #           modulus INTEGER, -- n | 
					
						
							|  |  |  |     #           publicExponent INTEGER -- e | 
					
						
							|  |  |  |     # } | 
					
						
							|  |  |  |     der = DerSequence().decode(encoded, nr_elements=2, only_ints_expected=True) | 
					
						
							|  |  |  |     return construct(der) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | def _import_subjectPublicKeyInfo(encoded, *kwargs): | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-06 22:02:28 +01:00
										 |  |  |     algoid, encoded_key, params = _expand_subject_public_key_info(encoded) | 
					
						
							|  |  |  |     if algoid != oid or params is not None: | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  |         raise ValueError("No RSA subjectPublicKeyInfo") | 
					
						
							|  |  |  |     return _import_pkcs1_public(encoded_key) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | def _import_x509_cert(encoded, *kwargs): | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     sp_info = _extract_subject_public_key_info(encoded) | 
					
						
							|  |  |  |     return _import_subjectPublicKeyInfo(sp_info) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | def _import_pkcs8(encoded, passphrase): | 
					
						
							| 
									
										
										
										
											2019-11-01 23:39:04 +01:00
										 |  |  |     from Crypto.IO import PKCS8 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  |     k = PKCS8.unwrap(encoded, passphrase) | 
					
						
							|  |  |  |     if k[0] != oid: | 
					
						
							|  |  |  |         raise ValueError("No PKCS#8 encoded RSA key") | 
					
						
							| 
									
										
										
										
											2016-02-04 18:50:49 +01:00
										 |  |  |     return _import_keyDER(k[1], passphrase) | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-04 18:50:49 +01:00
										 |  |  | def _import_keyDER(extern_key, passphrase): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     """Import an RSA key (public or private half), encoded in DER form.""" | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  |     decodings = (_import_pkcs1_private, | 
					
						
							|  |  |  |                  _import_pkcs1_public, | 
					
						
							|  |  |  |                  _import_subjectPublicKeyInfo, | 
					
						
							|  |  |  |                  _import_x509_cert, | 
					
						
							|  |  |  |                  _import_pkcs8) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     for decoding in decodings: | 
					
						
							|  |  |  |         try: | 
					
						
							|  |  |  |             return decoding(extern_key, passphrase) | 
					
						
							|  |  |  |         except ValueError: | 
					
						
							|  |  |  |             pass | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     raise ValueError("RSA key format is not supported") | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-01-23 13:33:08 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  | def _import_openssh_private_rsa(data, password): | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     from ._openssh import (import_openssh_private_generic, | 
					
						
							|  |  |  |                            read_bytes, read_string, check_padding) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     ssh_name, decrypted = import_openssh_private_generic(data, password) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     if ssh_name != "ssh-rsa": | 
					
						
							|  |  |  |         raise ValueError("This SSH key is not RSA") | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     n, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  |     e, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  |     d, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  |     iqmp, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  |     p, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  |     q, decrypted = read_bytes(decrypted) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     _, padded = read_string(decrypted)  # Comment | 
					
						
							|  |  |  |     check_padding(padded) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |     build = [Integer.from_bytes(x) for x in (n, e, d, q, p, iqmp)] | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |     return construct(build) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-04 18:50:49 +01:00
										 |  |  | def import_key(extern_key, passphrase=None): | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |     """Import an RSA key (public or private).
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Args: | 
					
						
							|  |  |  |       extern_key (string or byte string): | 
					
						
							|  |  |  |         The RSA key to import. | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |         The following formats are supported for an RSA **public key**: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |         - X.509 certificate (binary or PEM format) | 
					
						
							|  |  |  |         - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM | 
					
						
							|  |  |  |           encoding) | 
					
						
							|  |  |  |         - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding) | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |         - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |         The following formats are supported for an RSA **private key**: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |         - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding) | 
					
						
							|  |  |  |         - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo`` | 
					
						
							|  |  |  |           DER SEQUENCE (binary or PEM encoding) | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |         - OpenSSH (text format, introduced in `OpenSSH 6.5`_) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |         For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |       passphrase (string or byte string): | 
					
						
							|  |  |  |         For private keys only, the pass phrase that encrypts the key. | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Returns: An RSA key object (:class:`RsaKey`). | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  |     Raises: | 
					
						
							|  |  |  |       ValueError/IndexError/TypeError: | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         When the given key cannot be parsed (possibly because the pass | 
					
						
							|  |  |  |         phrase is wrong). | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt | 
					
						
							|  |  |  |     .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt | 
					
						
							|  |  |  |     .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt | 
					
						
							|  |  |  |     .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |     .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     """
 | 
					
						
							| 
									
										
										
										
											2017-08-14 07:22:48 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-11-01 23:39:04 +01:00
										 |  |  |     from Crypto.IO import PEM | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |     extern_key = tobytes(extern_key) | 
					
						
							|  |  |  |     if passphrase is not None: | 
					
						
							|  |  |  |         passphrase = tobytes(passphrase) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |     if extern_key.startswith(b'-----BEGIN OPENSSH PRIVATE KEY'): | 
					
						
							|  |  |  |         text_encoded = tostr(extern_key) | 
					
						
							|  |  |  |         openssh_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase) | 
					
						
							|  |  |  |         result = _import_openssh_private_rsa(openssh_encoded, passphrase) | 
					
						
							|  |  |  |         return result | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2018-11-04 11:31:40 +01:00
										 |  |  |     if extern_key.startswith(b'-----'): | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  |         # This is probably a PEM encoded key. | 
					
						
							|  |  |  |         (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase) | 
					
						
							|  |  |  |         if enc_flag: | 
					
						
							|  |  |  |             passphrase = None | 
					
						
							| 
									
										
										
										
											2016-02-04 18:50:49 +01:00
										 |  |  |         return _import_keyDER(der, passphrase) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2018-11-04 11:31:40 +01:00
										 |  |  |     if extern_key.startswith(b'ssh-rsa '): | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |         # This is probably an OpenSSH key | 
					
						
							|  |  |  |         keystring = binascii.a2b_base64(extern_key.split(b' ')[1]) | 
					
						
							|  |  |  |         keyparts = [] | 
					
						
							|  |  |  |         while len(keystring) > 4: | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  |             length = struct.unpack(">I", keystring[:4])[0] | 
					
						
							|  |  |  |             keyparts.append(keystring[4:4 + length]) | 
					
						
							|  |  |  |             keystring = keystring[4 + length:] | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |         e = Integer.from_bytes(keyparts[1]) | 
					
						
							|  |  |  |         n = Integer.from_bytes(keyparts[2]) | 
					
						
							|  |  |  |         return construct([n, e]) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-03-26 23:27:15 +01:00
										 |  |  |     if len(extern_key) > 0 and bord(extern_key[0]) == 0x30: | 
					
						
							| 
									
										
										
										
											2019-08-25 23:48:07 +02:00
										 |  |  |         # This is probably a DER encoded key | 
					
						
							|  |  |  |         return _import_keyDER(extern_key, passphrase) | 
					
						
							| 
									
										
										
										
											2015-03-11 11:26:10 -04:00
										 |  |  | 
 | 
					
						
							|  |  |  |     raise ValueError("RSA key format is not supported") | 
					
						
							| 
									
										
										
										
											2009-12-27 17:26:59 +01:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-08-25 23:58:43 +02:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2016-02-04 18:50:49 +01:00
										 |  |  | # Backward compatibility | 
					
						
							|  |  |  | importKey = import_key | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2013-06-15 23:25:49 +02:00
										 |  |  | #: `Object ID`_ for the RSA encryption algorithm. This OID often indicates | 
					
						
							|  |  |  | #: a generic RSA key, even when such key will be actually used for digital | 
					
						
							|  |  |  | #: signatures. | 
					
						
							|  |  |  | #: | 
					
						
							|  |  |  | #: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html | 
					
						
							|  |  |  | oid = "1.2.840.113549.1.1.1" |