You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

803 lines
25 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """RSA key generation code.
  15. Create new keys with the newkeys() function. It will give you a PublicKey and a
  16. PrivateKey object.
  17. Loading and saving keys requires the pyasn1 module. This module is imported as
  18. late as possible, such that other functionality will remain working in absence
  19. of pyasn1.
  20. .. note::
  21. Storing public and private keys via the `pickle` module is possible.
  22. However, it is insecure to load a key from an untrusted source.
  23. The pickle module is not secure against erroneous or maliciously
  24. constructed data. Never unpickle data received from an untrusted
  25. or unauthenticated source.
  26. """
  27. import logging
  28. import typing
  29. import warnings
  30. import rsa.prime
  31. import rsa.pem
  32. import rsa.common
  33. import rsa.randnum
  34. import rsa.core
  35. log = logging.getLogger(__name__)
  36. DEFAULT_EXPONENT = 65537
  37. class AbstractKey:
  38. """Abstract superclass for private and public keys."""
  39. __slots__ = ('n', 'e')
  40. def __init__(self, n: int, e: int) -> None:
  41. self.n = n
  42. self.e = e
  43. @classmethod
  44. def _load_pkcs1_pem(cls, keyfile: bytes) -> 'AbstractKey':
  45. """Loads a key in PKCS#1 PEM format, implement in a subclass.
  46. :param keyfile: contents of a PEM-encoded file that contains
  47. the public key.
  48. :type keyfile: bytes
  49. :return: the loaded key
  50. :rtype: AbstractKey
  51. """
  52. @classmethod
  53. def _load_pkcs1_der(cls, keyfile: bytes) -> 'AbstractKey':
  54. """Loads a key in PKCS#1 PEM format, implement in a subclass.
  55. :param keyfile: contents of a DER-encoded file that contains
  56. the public key.
  57. :type keyfile: bytes
  58. :return: the loaded key
  59. :rtype: AbstractKey
  60. """
  61. def _save_pkcs1_pem(self) -> bytes:
  62. """Saves the key in PKCS#1 PEM format, implement in a subclass.
  63. :returns: the PEM-encoded key.
  64. :rtype: bytes
  65. """
  66. def _save_pkcs1_der(self) -> bytes:
  67. """Saves the key in PKCS#1 DER format, implement in a subclass.
  68. :returns: the DER-encoded key.
  69. :rtype: bytes
  70. """
  71. @classmethod
  72. def load_pkcs1(cls, keyfile: bytes, format: str = 'PEM') -> 'AbstractKey':
  73. """Loads a key in PKCS#1 DER or PEM format.
  74. :param keyfile: contents of a DER- or PEM-encoded file that contains
  75. the key.
  76. :type keyfile: bytes
  77. :param format: the format of the file to load; 'PEM' or 'DER'
  78. :type format: str
  79. :return: the loaded key
  80. :rtype: AbstractKey
  81. """
  82. methods = {
  83. 'PEM': cls._load_pkcs1_pem,
  84. 'DER': cls._load_pkcs1_der,
  85. }
  86. method = cls._assert_format_exists(format, methods)
  87. return method(keyfile)
  88. @staticmethod
  89. def _assert_format_exists(file_format: str, methods: typing.Mapping[str, typing.Callable]) \
  90. -> typing.Callable:
  91. """Checks whether the given file format exists in 'methods'.
  92. """
  93. try:
  94. return methods[file_format]
  95. except KeyError:
  96. formats = ', '.join(sorted(methods.keys()))
  97. raise ValueError('Unsupported format: %r, try one of %s' % (file_format,
  98. formats))
  99. def save_pkcs1(self, format: str = 'PEM') -> bytes:
  100. """Saves the key in PKCS#1 DER or PEM format.
  101. :param format: the format to save; 'PEM' or 'DER'
  102. :type format: str
  103. :returns: the DER- or PEM-encoded key.
  104. :rtype: bytes
  105. """
  106. methods = {
  107. 'PEM': self._save_pkcs1_pem,
  108. 'DER': self._save_pkcs1_der,
  109. }
  110. method = self._assert_format_exists(format, methods)
  111. return method()
  112. def blind(self, message: int, r: int) -> int:
  113. """Performs blinding on the message using random number 'r'.
  114. :param message: the message, as integer, to blind.
  115. :type message: int
  116. :param r: the random number to blind with.
  117. :type r: int
  118. :return: the blinded message.
  119. :rtype: int
  120. The blinding is such that message = unblind(decrypt(blind(encrypt(message))).
  121. See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29
  122. """
  123. return (message * pow(r, self.e, self.n)) % self.n
  124. def unblind(self, blinded: int, r: int) -> int:
  125. """Performs blinding on the message using random number 'r'.
  126. :param blinded: the blinded message, as integer, to unblind.
  127. :param r: the random number to unblind with.
  128. :return: the original message.
  129. The blinding is such that message = unblind(decrypt(blind(encrypt(message))).
  130. See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29
  131. """
  132. return (rsa.common.inverse(r, self.n) * blinded) % self.n
  133. class PublicKey(AbstractKey):
  134. """Represents a public RSA key.
  135. This key is also known as the 'encryption key'. It contains the 'n' and 'e'
  136. values.
  137. Supports attributes as well as dictionary-like access. Attribute access is
  138. faster, though.
  139. >>> PublicKey(5, 3)
  140. PublicKey(5, 3)
  141. >>> key = PublicKey(5, 3)
  142. >>> key.n
  143. 5
  144. >>> key['n']
  145. 5
  146. >>> key.e
  147. 3
  148. >>> key['e']
  149. 3
  150. """
  151. __slots__ = ('n', 'e')
  152. def __getitem__(self, key: str) -> int:
  153. return getattr(self, key)
  154. def __repr__(self) -> str:
  155. return 'PublicKey(%i, %i)' % (self.n, self.e)
  156. def __getstate__(self) -> typing.Tuple[int, int]:
  157. """Returns the key as tuple for pickling."""
  158. return self.n, self.e
  159. def __setstate__(self, state: typing.Tuple[int, int]) -> None:
  160. """Sets the key from tuple."""
  161. self.n, self.e = state
  162. def __eq__(self, other: typing.Any) -> bool:
  163. if other is None:
  164. return False
  165. if not isinstance(other, PublicKey):
  166. return False
  167. return self.n == other.n and self.e == other.e
  168. def __ne__(self, other: typing.Any) -> bool:
  169. return not (self == other)
  170. def __hash__(self) -> int:
  171. return hash((self.n, self.e))
  172. @classmethod
  173. def _load_pkcs1_der(cls, keyfile: bytes) -> 'PublicKey':
  174. """Loads a key in PKCS#1 DER format.
  175. :param keyfile: contents of a DER-encoded file that contains the public
  176. key.
  177. :return: a PublicKey object
  178. First let's construct a DER encoded key:
  179. >>> import base64
  180. >>> b64der = 'MAwCBQCNGmYtAgMBAAE='
  181. >>> der = base64.standard_b64decode(b64der)
  182. This loads the file:
  183. >>> PublicKey._load_pkcs1_der(der)
  184. PublicKey(2367317549, 65537)
  185. """
  186. from pyasn1.codec.der import decoder
  187. from rsa.asn1 import AsnPubKey
  188. (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey())
  189. return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))
  190. def _save_pkcs1_der(self) -> bytes:
  191. """Saves the public key in PKCS#1 DER format.
  192. :returns: the DER-encoded public key.
  193. :rtype: bytes
  194. """
  195. from pyasn1.codec.der import encoder
  196. from rsa.asn1 import AsnPubKey
  197. # Create the ASN object
  198. asn_key = AsnPubKey()
  199. asn_key.setComponentByName('modulus', self.n)
  200. asn_key.setComponentByName('publicExponent', self.e)
  201. return encoder.encode(asn_key)
  202. @classmethod
  203. def _load_pkcs1_pem(cls, keyfile: bytes) -> 'PublicKey':
  204. """Loads a PKCS#1 PEM-encoded public key file.
  205. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and
  206. after the "-----END RSA PUBLIC KEY-----" lines is ignored.
  207. :param keyfile: contents of a PEM-encoded file that contains the public
  208. key.
  209. :return: a PublicKey object
  210. """
  211. der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY')
  212. return cls._load_pkcs1_der(der)
  213. def _save_pkcs1_pem(self) -> bytes:
  214. """Saves a PKCS#1 PEM-encoded public key file.
  215. :return: contents of a PEM-encoded file that contains the public key.
  216. :rtype: bytes
  217. """
  218. der = self._save_pkcs1_der()
  219. return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
  220. @classmethod
  221. def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> 'PublicKey':
  222. """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.
  223. These files can be recognised in that they start with BEGIN PUBLIC KEY
  224. rather than BEGIN RSA PUBLIC KEY.
  225. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
  226. after the "-----END PUBLIC KEY-----" lines is ignored.
  227. :param keyfile: contents of a PEM-encoded file that contains the public
  228. key, from OpenSSL.
  229. :type keyfile: bytes
  230. :return: a PublicKey object
  231. """
  232. der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
  233. return cls.load_pkcs1_openssl_der(der)
  234. @classmethod
  235. def load_pkcs1_openssl_der(cls, keyfile: bytes) -> 'PublicKey':
  236. """Loads a PKCS#1 DER-encoded public key file from OpenSSL.
  237. :param keyfile: contents of a DER-encoded file that contains the public
  238. key, from OpenSSL.
  239. :return: a PublicKey object
  240. """
  241. from rsa.asn1 import OpenSSLPubKey
  242. from pyasn1.codec.der import decoder
  243. from pyasn1.type import univ
  244. (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey())
  245. if keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'):
  246. raise TypeError("This is not a DER-encoded OpenSSL-compatible public key")
  247. return cls._load_pkcs1_der(keyinfo['key'][1:])
  248. class PrivateKey(AbstractKey):
  249. """Represents a private RSA key.
  250. This key is also known as the 'decryption key'. It contains the 'n', 'e',
  251. 'd', 'p', 'q' and other values.
  252. Supports attributes as well as dictionary-like access. Attribute access is
  253. faster, though.
  254. >>> PrivateKey(3247, 65537, 833, 191, 17)
  255. PrivateKey(3247, 65537, 833, 191, 17)
  256. exp1, exp2 and coef will be calculated:
  257. >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
  258. >>> pk.exp1
  259. 55063
  260. >>> pk.exp2
  261. 10095
  262. >>> pk.coef
  263. 50797
  264. """
  265. __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')
  266. def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None:
  267. AbstractKey.__init__(self, n, e)
  268. self.d = d
  269. self.p = p
  270. self.q = q
  271. # Calculate exponents and coefficient.
  272. self.exp1 = int(d % (p - 1))
  273. self.exp2 = int(d % (q - 1))
  274. self.coef = rsa.common.inverse(q, p)
  275. def __getitem__(self, key: str) -> int:
  276. return getattr(self, key)
  277. def __repr__(self) -> str:
  278. return 'PrivateKey(%i, %i, %i, %i, %i)' % (self.n, self.e, self.d, self.p, self.q)
  279. def __getstate__(self) -> typing.Tuple[int, int, int, int, int, int, int, int]:
  280. """Returns the key as tuple for pickling."""
  281. return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef
  282. def __setstate__(self, state: typing.Tuple[int, int, int, int, int, int, int, int]) -> None:
  283. """Sets the key from tuple."""
  284. self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state
  285. def __eq__(self, other: typing.Any) -> bool:
  286. if other is None:
  287. return False
  288. if not isinstance(other, PrivateKey):
  289. return False
  290. return (self.n == other.n and
  291. self.e == other.e and
  292. self.d == other.d and
  293. self.p == other.p and
  294. self.q == other.q and
  295. self.exp1 == other.exp1 and
  296. self.exp2 == other.exp2 and
  297. self.coef == other.coef)
  298. def __ne__(self, other: typing.Any) -> bool:
  299. return not (self == other)
  300. def __hash__(self) -> int:
  301. return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef))
  302. def _get_blinding_factor(self) -> int:
  303. for _ in range(1000):
  304. blind_r = rsa.randnum.randint(self.n - 1)
  305. if rsa.prime.are_relatively_prime(self.n, blind_r):
  306. return blind_r
  307. raise RuntimeError('unable to find blinding factor')
  308. def blinded_decrypt(self, encrypted: int) -> int:
  309. """Decrypts the message using blinding to prevent side-channel attacks.
  310. :param encrypted: the encrypted message
  311. :type encrypted: int
  312. :returns: the decrypted message
  313. :rtype: int
  314. """
  315. blind_r = self._get_blinding_factor()
  316. blinded = self.blind(encrypted, blind_r) # blind before decrypting
  317. decrypted = rsa.core.decrypt_int(blinded, self.d, self.n)
  318. return self.unblind(decrypted, blind_r)
  319. def blinded_encrypt(self, message: int) -> int:
  320. """Encrypts the message using blinding to prevent side-channel attacks.
  321. :param message: the message to encrypt
  322. :type message: int
  323. :returns: the encrypted message
  324. :rtype: int
  325. """
  326. blind_r = self._get_blinding_factor()
  327. blinded = self.blind(message, blind_r) # blind before encrypting
  328. encrypted = rsa.core.encrypt_int(blinded, self.d, self.n)
  329. return self.unblind(encrypted, blind_r)
  330. @classmethod
  331. def _load_pkcs1_der(cls, keyfile: bytes) -> 'PrivateKey':
  332. """Loads a key in PKCS#1 DER format.
  333. :param keyfile: contents of a DER-encoded file that contains the private
  334. key.
  335. :type keyfile: bytes
  336. :return: a PrivateKey object
  337. First let's construct a DER encoded key:
  338. >>> import base64
  339. >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt'
  340. >>> der = base64.standard_b64decode(b64der)
  341. This loads the file:
  342. >>> PrivateKey._load_pkcs1_der(der)
  343. PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
  344. """
  345. from pyasn1.codec.der import decoder
  346. (priv, _) = decoder.decode(keyfile)
  347. # ASN.1 contents of DER encoded private key:
  348. #
  349. # RSAPrivateKey ::= SEQUENCE {
  350. # version Version,
  351. # modulus INTEGER, -- n
  352. # publicExponent INTEGER, -- e
  353. # privateExponent INTEGER, -- d
  354. # prime1 INTEGER, -- p
  355. # prime2 INTEGER, -- q
  356. # exponent1 INTEGER, -- d mod (p-1)
  357. # exponent2 INTEGER, -- d mod (q-1)
  358. # coefficient INTEGER, -- (inverse of q) mod p
  359. # otherPrimeInfos OtherPrimeInfos OPTIONAL
  360. # }
  361. if priv[0] != 0:
  362. raise ValueError('Unable to read this file, version %s != 0' % priv[0])
  363. as_ints = map(int, priv[1:6])
  364. key = cls(*as_ints)
  365. exp1, exp2, coef = map(int, priv[6:9])
  366. if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef):
  367. warnings.warn(
  368. 'You have provided a malformed keyfile. Either the exponents '
  369. 'or the coefficient are incorrect. Using the correct values '
  370. 'instead.',
  371. UserWarning,
  372. )
  373. return key
  374. def _save_pkcs1_der(self) -> bytes:
  375. """Saves the private key in PKCS#1 DER format.
  376. :returns: the DER-encoded private key.
  377. :rtype: bytes
  378. """
  379. from pyasn1.type import univ, namedtype
  380. from pyasn1.codec.der import encoder
  381. class AsnPrivKey(univ.Sequence):
  382. componentType = namedtype.NamedTypes(
  383. namedtype.NamedType('version', univ.Integer()),
  384. namedtype.NamedType('modulus', univ.Integer()),
  385. namedtype.NamedType('publicExponent', univ.Integer()),
  386. namedtype.NamedType('privateExponent', univ.Integer()),
  387. namedtype.NamedType('prime1', univ.Integer()),
  388. namedtype.NamedType('prime2', univ.Integer()),
  389. namedtype.NamedType('exponent1', univ.Integer()),
  390. namedtype.NamedType('exponent2', univ.Integer()),
  391. namedtype.NamedType('coefficient', univ.Integer()),
  392. )
  393. # Create the ASN object
  394. asn_key = AsnPrivKey()
  395. asn_key.setComponentByName('version', 0)
  396. asn_key.setComponentByName('modulus', self.n)
  397. asn_key.setComponentByName('publicExponent', self.e)
  398. asn_key.setComponentByName('privateExponent', self.d)
  399. asn_key.setComponentByName('prime1', self.p)
  400. asn_key.setComponentByName('prime2', self.q)
  401. asn_key.setComponentByName('exponent1', self.exp1)
  402. asn_key.setComponentByName('exponent2', self.exp2)
  403. asn_key.setComponentByName('coefficient', self.coef)
  404. return encoder.encode(asn_key)
  405. @classmethod
  406. def _load_pkcs1_pem(cls, keyfile: bytes) -> 'PrivateKey':
  407. """Loads a PKCS#1 PEM-encoded private key file.
  408. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and
  409. after the "-----END RSA PRIVATE KEY-----" lines is ignored.
  410. :param keyfile: contents of a PEM-encoded file that contains the private
  411. key.
  412. :type keyfile: bytes
  413. :return: a PrivateKey object
  414. """
  415. der = rsa.pem.load_pem(keyfile, b'RSA PRIVATE KEY')
  416. return cls._load_pkcs1_der(der)
  417. def _save_pkcs1_pem(self) -> bytes:
  418. """Saves a PKCS#1 PEM-encoded private key file.
  419. :return: contents of a PEM-encoded file that contains the private key.
  420. :rtype: bytes
  421. """
  422. der = self._save_pkcs1_der()
  423. return rsa.pem.save_pem(der, b'RSA PRIVATE KEY')
  424. def find_p_q(nbits: int,
  425. getprime_func: typing.Callable[[int], int] = rsa.prime.getprime,
  426. accurate: bool = True) -> typing.Tuple[int, int]:
  427. """Returns a tuple of two different primes of nbits bits each.
  428. The resulting p * q has exacty 2 * nbits bits, and the returned p and q
  429. will not be equal.
  430. :param nbits: the number of bits in each of p and q.
  431. :param getprime_func: the getprime function, defaults to
  432. :py:func:`rsa.prime.getprime`.
  433. *Introduced in Python-RSA 3.1*
  434. :param accurate: whether to enable accurate mode or not.
  435. :returns: (p, q), where p > q
  436. >>> (p, q) = find_p_q(128)
  437. >>> from rsa import common
  438. >>> common.bit_size(p * q)
  439. 256
  440. When not in accurate mode, the number of bits can be slightly less
  441. >>> (p, q) = find_p_q(128, accurate=False)
  442. >>> from rsa import common
  443. >>> common.bit_size(p * q) <= 256
  444. True
  445. >>> common.bit_size(p * q) > 240
  446. True
  447. """
  448. total_bits = nbits * 2
  449. # Make sure that p and q aren't too close or the factoring programs can
  450. # factor n.
  451. shift = nbits // 16
  452. pbits = nbits + shift
  453. qbits = nbits - shift
  454. # Choose the two initial primes
  455. log.debug('find_p_q(%i): Finding p', nbits)
  456. p = getprime_func(pbits)
  457. log.debug('find_p_q(%i): Finding q', nbits)
  458. q = getprime_func(qbits)
  459. def is_acceptable(p: int, q: int) -> bool:
  460. """Returns True iff p and q are acceptable:
  461. - p and q differ
  462. - (p * q) has the right nr of bits (when accurate=True)
  463. """
  464. if p == q:
  465. return False
  466. if not accurate:
  467. return True
  468. # Make sure we have just the right amount of bits
  469. found_size = rsa.common.bit_size(p * q)
  470. return total_bits == found_size
  471. # Keep choosing other primes until they match our requirements.
  472. change_p = False
  473. while not is_acceptable(p, q):
  474. # Change p on one iteration and q on the other
  475. if change_p:
  476. p = getprime_func(pbits)
  477. else:
  478. q = getprime_func(qbits)
  479. change_p = not change_p
  480. # We want p > q as described on
  481. # http://www.di-mgt.com.au/rsa_alg.html#crt
  482. return max(p, q), min(p, q)
  483. def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tuple[int, int]:
  484. """Calculates an encryption and a decryption key given p, q and an exponent,
  485. and returns them as a tuple (e, d)
  486. :param p: the first large prime
  487. :param q: the second large prime
  488. :param exponent: the exponent for the key; only change this if you know
  489. what you're doing, as the exponent influences how difficult your
  490. private key can be cracked. A very common choice for e is 65537.
  491. :type exponent: int
  492. """
  493. phi_n = (p - 1) * (q - 1)
  494. try:
  495. d = rsa.common.inverse(exponent, phi_n)
  496. except rsa.common.NotRelativePrimeError as ex:
  497. raise rsa.common.NotRelativePrimeError(
  498. exponent, phi_n, ex.d,
  499. msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" %
  500. (exponent, phi_n, ex.d))
  501. if (exponent * d) % phi_n != 1:
  502. raise ValueError("e (%d) and d (%d) are not mult. inv. modulo "
  503. "phi_n (%d)" % (exponent, d, phi_n))
  504. return exponent, d
  505. def calculate_keys(p: int, q: int) -> typing.Tuple[int, int]:
  506. """Calculates an encryption and a decryption key given p and q, and
  507. returns them as a tuple (e, d)
  508. :param p: the first large prime
  509. :param q: the second large prime
  510. :return: tuple (e, d) with the encryption and decryption exponents.
  511. """
  512. return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT)
  513. def gen_keys(nbits: int,
  514. getprime_func: typing.Callable[[int], int],
  515. accurate: bool = True,
  516. exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[int, int, int, int]:
  517. """Generate RSA keys of nbits bits. Returns (p, q, e, d).
  518. Note: this can take a long time, depending on the key size.
  519. :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and
  520. ``q`` will use ``nbits/2`` bits.
  521. :param getprime_func: either :py:func:`rsa.prime.getprime` or a function
  522. with similar signature.
  523. :param exponent: the exponent for the key; only change this if you know
  524. what you're doing, as the exponent influences how difficult your
  525. private key can be cracked. A very common choice for e is 65537.
  526. :type exponent: int
  527. """
  528. # Regenerate p and q values, until calculate_keys doesn't raise a
  529. # ValueError.
  530. while True:
  531. (p, q) = find_p_q(nbits // 2, getprime_func, accurate)
  532. try:
  533. (e, d) = calculate_keys_custom_exponent(p, q, exponent=exponent)
  534. break
  535. except ValueError:
  536. pass
  537. return p, q, e, d
  538. def newkeys(nbits: int,
  539. accurate: bool = True,
  540. poolsize: int = 1,
  541. exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[PublicKey, PrivateKey]:
  542. """Generates public and private keys, and returns them as (pub, priv).
  543. The public key is also known as the 'encryption key', and is a
  544. :py:class:`rsa.PublicKey` object. The private key is also known as the
  545. 'decryption key' and is a :py:class:`rsa.PrivateKey` object.
  546. :param nbits: the number of bits required to store ``n = p*q``.
  547. :param accurate: when True, ``n`` will have exactly the number of bits you
  548. asked for. However, this makes key generation much slower. When False,
  549. `n`` may have slightly less bits.
  550. :param poolsize: the number of processes to use to generate the prime
  551. numbers. If set to a number > 1, a parallel algorithm will be used.
  552. This requires Python 2.6 or newer.
  553. :param exponent: the exponent for the key; only change this if you know
  554. what you're doing, as the exponent influences how difficult your
  555. private key can be cracked. A very common choice for e is 65537.
  556. :type exponent: int
  557. :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`)
  558. The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires
  559. Python 2.6 or newer.
  560. """
  561. if nbits < 16:
  562. raise ValueError('Key too small')
  563. if poolsize < 1:
  564. raise ValueError('Pool size (%i) should be >= 1' % poolsize)
  565. # Determine which getprime function to use
  566. if poolsize > 1:
  567. from rsa import parallel
  568. def getprime_func(nbits: int) -> int:
  569. return parallel.getprime(nbits, poolsize=poolsize)
  570. else:
  571. getprime_func = rsa.prime.getprime
  572. # Generate the key components
  573. (p, q, e, d) = gen_keys(nbits, getprime_func, accurate=accurate, exponent=exponent)
  574. # Create the key objects
  575. n = p * q
  576. return (
  577. PublicKey(n, e),
  578. PrivateKey(n, e, d, p, q)
  579. )
  580. __all__ = ['PublicKey', 'PrivateKey', 'newkeys']
  581. if __name__ == '__main__':
  582. import doctest
  583. try:
  584. for count in range(100):
  585. (failures, tests) = doctest.testmod()
  586. if failures:
  587. break
  588. if (count % 10 == 0 and count) or count == 1:
  589. print('%i times' % count)
  590. except KeyboardInterrupt:
  591. print('Aborted')
  592. else:
  593. print('Doctests done')