RSA.py 28 KB

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