key.py 24 KB

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