RSA.py 28 KB

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