RSA.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. # -*- coding: utf-8 -*-
  2. # ===================================================================
  3. #
  4. # Copyright (c) 2016, Legrandin <helderijs@gmail.com>
  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. __all__ = ['generate', 'construct', 'import_key',
  32. 'RsaKey', 'oid']
  33. import binascii
  34. import struct
  35. from Crypto import Random
  36. from Crypto.Util.py3compat import tobytes, bord, tostr
  37. from Crypto.Util.asn1 import DerSequence
  38. from Crypto.Math.Numbers import Integer
  39. from Crypto.Math.Primality import (test_probable_prime,
  40. generate_probable_prime, COMPOSITE)
  41. from Crypto.PublicKey import (_expand_subject_public_key_info,
  42. _create_subject_public_key_info,
  43. _extract_subject_public_key_info)
  44. class RsaKey(object):
  45. r"""Class defining an actual RSA key.
  46. Do not instantiate directly.
  47. Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
  48. :ivar n: RSA modulus
  49. :vartype n: integer
  50. :ivar e: RSA public exponent
  51. :vartype e: integer
  52. :ivar d: RSA private exponent
  53. :vartype d: integer
  54. :ivar p: First factor of the RSA modulus
  55. :vartype p: integer
  56. :ivar q: Second factor of the RSA modulus
  57. :vartype q: integer
  58. :ivar u: Chinese remainder component (:math:`p^{-1} \text{mod } q`)
  59. :vartype q: integer
  60. :undocumented: exportKey, publickey
  61. """
  62. def __init__(self, **kwargs):
  63. """Build an RSA key.
  64. :Keywords:
  65. n : integer
  66. The modulus.
  67. e : integer
  68. The public exponent.
  69. d : integer
  70. The private exponent. Only required for private keys.
  71. p : integer
  72. The first factor of the modulus. Only required for private keys.
  73. q : integer
  74. The second factor of the modulus. Only required for private keys.
  75. u : integer
  76. The CRT coefficient (inverse of p modulo q). Only required for
  77. private keys.
  78. """
  79. input_set = set(kwargs.keys())
  80. public_set = set(('n', 'e'))
  81. private_set = public_set | set(('p', 'q', 'd', 'u'))
  82. if input_set not in (private_set, public_set):
  83. raise ValueError("Some RSA components are missing")
  84. for component, value in kwargs.items():
  85. setattr(self, "_" + component, value)
  86. if input_set == private_set:
  87. self._dp = self._d % (self._p - 1) # = (e⁻¹) mod (p-1)
  88. self._dq = self._d % (self._q - 1) # = (e⁻¹) mod (q-1)
  89. @property
  90. def n(self):
  91. return int(self._n)
  92. @property
  93. def e(self):
  94. return int(self._e)
  95. @property
  96. def d(self):
  97. if not self.has_private():
  98. raise AttributeError("No private exponent available for public keys")
  99. return int(self._d)
  100. @property
  101. def p(self):
  102. if not self.has_private():
  103. raise AttributeError("No CRT component 'p' available for public keys")
  104. return int(self._p)
  105. @property
  106. def q(self):
  107. if not self.has_private():
  108. raise AttributeError("No CRT component 'q' available for public keys")
  109. return int(self._q)
  110. @property
  111. def u(self):
  112. if not self.has_private():
  113. raise AttributeError("No CRT component 'u' available for public keys")
  114. return int(self._u)
  115. def size_in_bits(self):
  116. """Size of the RSA modulus in bits"""
  117. return self._n.size_in_bits()
  118. def size_in_bytes(self):
  119. """The minimal amount of bytes that can hold the RSA modulus"""
  120. return (self._n.size_in_bits() - 1) // 8 + 1
  121. def _encrypt(self, plaintext):
  122. if not 0 <= plaintext < self._n:
  123. raise ValueError("Plaintext too large")
  124. return int(pow(Integer(plaintext), self._e, self._n))
  125. def _decrypt(self, ciphertext):
  126. if not 0 <= ciphertext < self._n:
  127. raise ValueError("Ciphertext too large")
  128. if not self.has_private():
  129. raise TypeError("This is not a private key")
  130. # Blinded RSA decryption (to prevent timing attacks):
  131. # Step 1: Generate random secret blinding factor r,
  132. # such that 0 < r < n-1
  133. r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
  134. # Step 2: Compute c' = c * r**e mod n
  135. cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
  136. # Step 3: Compute m' = c'**d mod n (normal RSA decryption)
  137. m1 = pow(cp, self._dp, self._p)
  138. m2 = pow(cp, self._dq, self._q)
  139. h = ((m2 - m1) * self._u) % self._q
  140. mp = h * self._p + m1
  141. # Step 4: Compute m = m**(r-1) mod n
  142. result = (r.inverse(self._n) * mp) % self._n
  143. # Verify no faults occurred
  144. if ciphertext != pow(result, self._e, self._n):
  145. raise ValueError("Fault detected in RSA decryption")
  146. return result
  147. def has_private(self):
  148. """Whether this is an RSA private key"""
  149. return hasattr(self, "_d")
  150. def can_encrypt(self): # legacy
  151. return True
  152. def can_sign(self): # legacy
  153. return True
  154. def public_key(self):
  155. """A matching RSA public key.
  156. Returns:
  157. a new :class:`RsaKey` object
  158. """
  159. return RsaKey(n=self._n, e=self._e)
  160. def __eq__(self, other):
  161. if self.has_private() != other.has_private():
  162. return False
  163. if self.n != other.n or self.e != other.e:
  164. return False
  165. if not self.has_private():
  166. return True
  167. return (self.d == other.d)
  168. def __ne__(self, other):
  169. return not (self == other)
  170. def __getstate__(self):
  171. # RSA key is not pickable
  172. from pickle import PicklingError
  173. raise PicklingError
  174. def __repr__(self):
  175. if self.has_private():
  176. extra = ", d=%d, p=%d, q=%d, u=%d" % (int(self._d), int(self._p),
  177. int(self._q), int(self._u))
  178. else:
  179. extra = ""
  180. return "RsaKey(n=%d, e=%d%s)" % (int(self._n), int(self._e), extra)
  181. def __str__(self):
  182. if self.has_private():
  183. key_type = "Private"
  184. else:
  185. key_type = "Public"
  186. return "%s RSA key at 0x%X" % (key_type, id(self))
  187. def export_key(self, format='PEM', passphrase=None, pkcs=1,
  188. protection=None, randfunc=None):
  189. """Export this RSA key.
  190. Args:
  191. format (string):
  192. The format to use for wrapping the key:
  193. - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_.
  194. - *'DER'*. Binary encoding.
  195. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
  196. Only suitable for public keys (not private keys).
  197. passphrase (string):
  198. (*For private keys only*) The pass phrase used for protecting the output.
  199. pkcs (integer):
  200. (*For private keys only*) The ASN.1 structure to use for
  201. serializing the key. Note that even in case of PEM
  202. encoding, there is an inner ASN.1 DER structure.
  203. With ``pkcs=1`` (*default*), the private key is encoded in a
  204. simple `PKCS#1`_ structure (``RSAPrivateKey``).
  205. With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure
  206. (``PrivateKeyInfo``).
  207. .. note::
  208. This parameter is ignored for a public key.
  209. For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo``
  210. structure is always used.
  211. protection (string):
  212. (*For private keys only*)
  213. The encryption scheme to use for protecting the private key.
  214. If ``None`` (default), the behavior depends on :attr:`format`:
  215. - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
  216. scheme is used. The following operations are performed:
  217. 1. A 16 byte Triple DES key is derived from the passphrase
  218. using :func:`Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt,
  219. and 1 000 iterations of :mod:`Crypto.Hash.HMAC`.
  220. 2. The private key is encrypted using CBC.
  221. 3. The encrypted key is encoded according to PKCS#8.
  222. - For *'PEM'*, the obsolete PEM encryption scheme is used.
  223. It is based on MD5 for key derivation, and Triple DES for encryption.
  224. Specifying a value for :attr:`protection` is only meaningful for PKCS#8
  225. (that is, ``pkcs=8``) and only if a pass phrase is present too.
  226. The supported schemes for PKCS#8 are listed in the
  227. :mod:`Crypto.IO.PKCS8` module (see :attr:`wrap_algo` parameter).
  228. randfunc (callable):
  229. A function that provides random bytes. Only used for PEM encoding.
  230. The default is :func:`Crypto.Random.get_random_bytes`.
  231. Returns:
  232. byte string: the encoded key
  233. Raises:
  234. ValueError:when the format is unknown or when you try to encrypt a private
  235. key with *DER* format and PKCS#1.
  236. .. warning::
  237. If you don't provide a pass phrase, the private key will be
  238. exported in the clear!
  239. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  240. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  241. .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
  242. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  243. """
  244. if passphrase is not None:
  245. passphrase = tobytes(passphrase)
  246. if randfunc is None:
  247. randfunc = Random.get_random_bytes
  248. if format == 'OpenSSH':
  249. e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)]
  250. if bord(e_bytes[0]) & 0x80:
  251. e_bytes = b'\x00' + e_bytes
  252. if bord(n_bytes[0]) & 0x80:
  253. n_bytes = b'\x00' + n_bytes
  254. keyparts = [b'ssh-rsa', e_bytes, n_bytes]
  255. keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
  256. return b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1]
  257. # DER format is always used, even in case of PEM, which simply
  258. # encodes it into BASE64.
  259. if self.has_private():
  260. binary_key = DerSequence([0,
  261. self.n,
  262. self.e,
  263. self.d,
  264. self.p,
  265. self.q,
  266. self.d % (self.p-1),
  267. self.d % (self.q-1),
  268. Integer(self.q).inverse(self.p)
  269. ]).encode()
  270. if pkcs == 1:
  271. key_type = 'RSA PRIVATE KEY'
  272. if format == 'DER' and passphrase:
  273. raise ValueError("PKCS#1 private key cannot be encrypted")
  274. else: # PKCS#8
  275. from Crypto.IO import PKCS8
  276. if format == 'PEM' and protection is None:
  277. key_type = 'PRIVATE KEY'
  278. binary_key = PKCS8.wrap(binary_key, oid, None)
  279. else:
  280. key_type = 'ENCRYPTED PRIVATE KEY'
  281. if not protection:
  282. protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
  283. binary_key = PKCS8.wrap(binary_key, oid,
  284. passphrase, protection)
  285. passphrase = None
  286. else:
  287. key_type = "PUBLIC KEY"
  288. binary_key = _create_subject_public_key_info(oid,
  289. DerSequence([self.n,
  290. self.e])
  291. )
  292. if format == 'DER':
  293. return binary_key
  294. if format == 'PEM':
  295. from Crypto.IO import PEM
  296. pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc)
  297. return tobytes(pem_str)
  298. raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
  299. # Backward compatibility
  300. exportKey = export_key
  301. publickey = public_key
  302. # Methods defined in PyCrypto that we don't support anymore
  303. def sign(self, M, K):
  304. raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
  305. def verify(self, M, signature):
  306. raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
  307. def encrypt(self, plaintext, K):
  308. raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
  309. def decrypt(self, ciphertext):
  310. raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
  311. def blind(self, M, B):
  312. raise NotImplementedError
  313. def unblind(self, M, B):
  314. raise NotImplementedError
  315. def size(self):
  316. raise NotImplementedError
  317. def generate(bits, randfunc=None, e=65537):
  318. """Create a new RSA key pair.
  319. The algorithm closely follows NIST `FIPS 186-4`_ in its
  320. sections B.3.1 and B.3.3. The modulus is the product of
  321. two non-strong probable primes.
  322. Each prime passes a suitable number of Miller-Rabin tests
  323. with random bases and a single Lucas test.
  324. Args:
  325. bits (integer):
  326. Key length, or size (in bits) of the RSA modulus.
  327. It must be at least 1024, but **2048 is recommended.**
  328. The FIPS standard only defines 1024, 2048 and 3072.
  329. randfunc (callable):
  330. Function that returns random bytes.
  331. The default is :func:`Crypto.Random.get_random_bytes`.
  332. e (integer):
  333. Public RSA exponent. It must be an odd positive integer.
  334. It is typically a small number with very few ones in its
  335. binary representation.
  336. The FIPS standard requires the public exponent to be
  337. at least 65537 (the default).
  338. Returns: an RSA key object (:class:`RsaKey`, with private key).
  339. .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  340. """
  341. if bits < 1024:
  342. raise ValueError("RSA modulus length must be >= 1024")
  343. if e % 2 == 0 or e < 3:
  344. raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
  345. if randfunc is None:
  346. randfunc = Random.get_random_bytes
  347. d = n = Integer(1)
  348. e = Integer(e)
  349. while n.size_in_bits() != bits and d < (1 << (bits // 2)):
  350. # Generate the prime factors of n: p and q.
  351. # By construciton, their product is always
  352. # 2^{bits-1} < p*q < 2^bits.
  353. size_q = bits // 2
  354. size_p = bits - size_q
  355. min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt()
  356. if size_q != size_p:
  357. min_p = (Integer(1) << (2 * size_p - 1)).sqrt()
  358. def filter_p(candidate):
  359. return candidate > min_p and (candidate - 1).gcd(e) == 1
  360. p = generate_probable_prime(exact_bits=size_p,
  361. randfunc=randfunc,
  362. prime_filter=filter_p)
  363. min_distance = Integer(1) << (bits // 2 - 100)
  364. def filter_q(candidate):
  365. return (candidate > min_q and
  366. (candidate - 1).gcd(e) == 1 and
  367. abs(candidate - p) > min_distance)
  368. q = generate_probable_prime(exact_bits=size_q,
  369. randfunc=randfunc,
  370. prime_filter=filter_q)
  371. n = p * q
  372. lcm = (p - 1).lcm(q - 1)
  373. d = e.inverse(lcm)
  374. if p > q:
  375. p, q = q, p
  376. u = p.inverse(q)
  377. return RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
  378. def construct(rsa_components, consistency_check=True):
  379. r"""Construct an RSA key from a tuple of valid RSA components.
  380. The modulus **n** must be the product of two primes.
  381. The public exponent **e** must be odd and larger than 1.
  382. In case of a private key, the following equations must apply:
  383. .. math::
  384. \begin{align}
  385. p*q &= n \\
  386. e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\
  387. p*u &\equiv 1 ( \text{mod } q)
  388. \end{align}
  389. Args:
  390. rsa_components (tuple):
  391. A tuple of integers, with at least 2 and no
  392. more than 6 items. The items come in the following order:
  393. 1. RSA modulus *n*.
  394. 2. Public exponent *e*.
  395. 3. Private exponent *d*.
  396. Only required if the key is private.
  397. 4. First factor of *n* (*p*).
  398. Optional, but the other factor *q* must also be present.
  399. 5. Second factor of *n* (*q*). Optional.
  400. 6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional.
  401. consistency_check (boolean):
  402. If ``True``, the library will verify that the provided components
  403. fulfil the main RSA properties.
  404. Raises:
  405. ValueError: when the key being imported fails the most basic RSA validity checks.
  406. Returns: An RSA key object (:class:`RsaKey`).
  407. """
  408. class InputComps(object):
  409. pass
  410. input_comps = InputComps()
  411. for (comp, value) in zip(('n', 'e', 'd', 'p', 'q', 'u'), rsa_components):
  412. setattr(input_comps, comp, Integer(value))
  413. n = input_comps.n
  414. e = input_comps.e
  415. if not hasattr(input_comps, 'd'):
  416. key = RsaKey(n=n, e=e)
  417. else:
  418. d = input_comps.d
  419. if hasattr(input_comps, 'q'):
  420. p = input_comps.p
  421. q = input_comps.q
  422. else:
  423. # Compute factors p and q from the private exponent d.
  424. # We assume that n has no more than two factors.
  425. # See 8.2.2(i) in Handbook of Applied Cryptography.
  426. ktot = d * e - 1
  427. # The quantity d*e-1 is a multiple of phi(n), even,
  428. # and can be represented as t*2^s.
  429. t = ktot
  430. while t % 2 == 0:
  431. t //= 2
  432. # Cycle through all multiplicative inverses in Zn.
  433. # The algorithm is non-deterministic, but there is a 50% chance
  434. # any candidate a leads to successful factoring.
  435. # See "Digitalized Signatures and Public Key Functions as Intractable
  436. # as Factorization", M. Rabin, 1979
  437. spotted = False
  438. a = Integer(2)
  439. while not spotted and a < 100:
  440. k = Integer(t)
  441. # Cycle through all values a^{t*2^i}=a^k
  442. while k < ktot:
  443. cand = pow(a, k, n)
  444. # Check if a^k is a non-trivial root of unity (mod n)
  445. if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
  446. # We have found a number such that (cand-1)(cand+1)=0 (mod n).
  447. # Either of the terms divides n.
  448. p = Integer(n).gcd(cand + 1)
  449. spotted = True
  450. break
  451. k *= 2
  452. # This value was not any good... let's try another!
  453. a += 2
  454. if not spotted:
  455. raise ValueError("Unable to compute factors p and q from exponent d.")
  456. # Found !
  457. assert ((n % p) == 0)
  458. q = n // p
  459. if hasattr(input_comps, 'u'):
  460. u = input_comps.u
  461. else:
  462. u = p.inverse(q)
  463. # Build key object
  464. key = RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
  465. # Verify consistency of the key
  466. if consistency_check:
  467. # Modulus and public exponent must be coprime
  468. if e <= 1 or e >= n:
  469. raise ValueError("Invalid RSA public exponent")
  470. if Integer(n).gcd(e) != 1:
  471. raise ValueError("RSA public exponent is not coprime to modulus")
  472. # For RSA, modulus must be odd
  473. if not n & 1:
  474. raise ValueError("RSA modulus is not odd")
  475. if key.has_private():
  476. # Modulus and private exponent must be coprime
  477. if d <= 1 or d >= n:
  478. raise ValueError("Invalid RSA private exponent")
  479. if Integer(n).gcd(d) != 1:
  480. raise ValueError("RSA private exponent is not coprime to modulus")
  481. # Modulus must be product of 2 primes
  482. if p * q != n:
  483. raise ValueError("RSA factors do not match modulus")
  484. if test_probable_prime(p) == COMPOSITE:
  485. raise ValueError("RSA factor p is composite")
  486. if test_probable_prime(q) == COMPOSITE:
  487. raise ValueError("RSA factor q is composite")
  488. # See Carmichael theorem
  489. phi = (p - 1) * (q - 1)
  490. lcm = phi // (p - 1).gcd(q - 1)
  491. if (e * d % int(lcm)) != 1:
  492. raise ValueError("Invalid RSA condition")
  493. if hasattr(key, 'u'):
  494. # CRT coefficient
  495. if u <= 1 or u >= q:
  496. raise ValueError("Invalid RSA component u")
  497. if (p * u % q) != 1:
  498. raise ValueError("Invalid RSA component u with p")
  499. return key
  500. def _import_pkcs1_private(encoded, *kwargs):
  501. # RSAPrivateKey ::= SEQUENCE {
  502. # version Version,
  503. # modulus INTEGER, -- n
  504. # publicExponent INTEGER, -- e
  505. # privateExponent INTEGER, -- d
  506. # prime1 INTEGER, -- p
  507. # prime2 INTEGER, -- q
  508. # exponent1 INTEGER, -- d mod (p-1)
  509. # exponent2 INTEGER, -- d mod (q-1)
  510. # coefficient INTEGER -- (inverse of q) mod p
  511. # }
  512. #
  513. # Version ::= INTEGER
  514. der = DerSequence().decode(encoded, nr_elements=9, only_ints_expected=True)
  515. if der[0] != 0:
  516. raise ValueError("No PKCS#1 encoding of an RSA private key")
  517. return construct(der[1:6] + [Integer(der[4]).inverse(der[5])])
  518. def _import_pkcs1_public(encoded, *kwargs):
  519. # RSAPublicKey ::= SEQUENCE {
  520. # modulus INTEGER, -- n
  521. # publicExponent INTEGER -- e
  522. # }
  523. der = DerSequence().decode(encoded, nr_elements=2, only_ints_expected=True)
  524. return construct(der)
  525. def _import_subjectPublicKeyInfo(encoded, *kwargs):
  526. algoid, encoded_key, params = _expand_subject_public_key_info(encoded)
  527. if algoid != oid or params is not None:
  528. raise ValueError("No RSA subjectPublicKeyInfo")
  529. return _import_pkcs1_public(encoded_key)
  530. def _import_x509_cert(encoded, *kwargs):
  531. sp_info = _extract_subject_public_key_info(encoded)
  532. return _import_subjectPublicKeyInfo(sp_info)
  533. def _import_pkcs8(encoded, passphrase):
  534. from Crypto.IO import PKCS8
  535. k = PKCS8.unwrap(encoded, passphrase)
  536. if k[0] != oid:
  537. raise ValueError("No PKCS#8 encoded RSA key")
  538. return _import_keyDER(k[1], passphrase)
  539. def _import_keyDER(extern_key, passphrase):
  540. """Import an RSA key (public or private half), encoded in DER form."""
  541. decodings = (_import_pkcs1_private,
  542. _import_pkcs1_public,
  543. _import_subjectPublicKeyInfo,
  544. _import_x509_cert,
  545. _import_pkcs8)
  546. for decoding in decodings:
  547. try:
  548. return decoding(extern_key, passphrase)
  549. except ValueError:
  550. pass
  551. raise ValueError("RSA key format is not supported")
  552. def _import_openssh_private_rsa(data, password):
  553. from ._openssh import (import_openssh_private_generic,
  554. read_bytes, read_string, check_padding)
  555. ssh_name, decrypted = import_openssh_private_generic(data, password)
  556. if ssh_name != "ssh-rsa":
  557. raise ValueError("This SSH key is not RSA")
  558. n, decrypted = read_bytes(decrypted)
  559. e, decrypted = read_bytes(decrypted)
  560. d, decrypted = read_bytes(decrypted)
  561. iqmp, decrypted = read_bytes(decrypted)
  562. p, decrypted = read_bytes(decrypted)
  563. q, decrypted = read_bytes(decrypted)
  564. _, padded = read_string(decrypted) # Comment
  565. check_padding(padded)
  566. build = [Integer.from_bytes(x) for x in (n, e, d, q, p, iqmp)]
  567. return construct(build)
  568. def import_key(extern_key, passphrase=None):
  569. """Import an RSA key (public or private).
  570. Args:
  571. extern_key (string or byte string):
  572. The RSA key to import.
  573. The following formats are supported for an RSA **public key**:
  574. - X.509 certificate (binary or PEM format)
  575. - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
  576. encoding)
  577. - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
  578. - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
  579. The following formats are supported for an RSA **private key**:
  580. - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
  581. - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
  582. DER SEQUENCE (binary or PEM encoding)
  583. - OpenSSH (text format, introduced in `OpenSSH 6.5`_)
  584. For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
  585. passphrase (string or byte string):
  586. For private keys only, the pass phrase that encrypts the key.
  587. Returns: An RSA key object (:class:`RsaKey`).
  588. Raises:
  589. ValueError/IndexError/TypeError:
  590. When the given key cannot be parsed (possibly because the pass
  591. phrase is wrong).
  592. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  593. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  594. .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
  595. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  596. .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
  597. """
  598. from Crypto.IO import PEM
  599. extern_key = tobytes(extern_key)
  600. if passphrase is not None:
  601. passphrase = tobytes(passphrase)
  602. if extern_key.startswith(b'-----BEGIN OPENSSH PRIVATE KEY'):
  603. text_encoded = tostr(extern_key)
  604. openssh_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase)
  605. result = _import_openssh_private_rsa(openssh_encoded, passphrase)
  606. return result
  607. if extern_key.startswith(b'-----'):
  608. # This is probably a PEM encoded key.
  609. (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
  610. if enc_flag:
  611. passphrase = None
  612. return _import_keyDER(der, passphrase)
  613. if extern_key.startswith(b'ssh-rsa '):
  614. # This is probably an OpenSSH key
  615. keystring = binascii.a2b_base64(extern_key.split(b' ')[1])
  616. keyparts = []
  617. while len(keystring) > 4:
  618. length = struct.unpack(">I", keystring[:4])[0]
  619. keyparts.append(keystring[4:4 + length])
  620. keystring = keystring[4 + length:]
  621. e = Integer.from_bytes(keyparts[1])
  622. n = Integer.from_bytes(keyparts[2])
  623. return construct([n, e])
  624. if len(extern_key) > 0 and bord(extern_key[0]) == 0x30:
  625. # This is probably a DER encoded key
  626. return _import_keyDER(extern_key, passphrase)
  627. raise ValueError("RSA key format is not supported")
  628. # Backward compatibility
  629. importKey = import_key
  630. #: `Object ID`_ for the RSA encryption algorithm. This OID often indicates
  631. #: a generic RSA key, even when such key will be actually used for digital
  632. #: signatures.
  633. #:
  634. #: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html
  635. oid = "1.2.840.113549.1.1.1"