RSA.py 29 KB

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