key.py 22 KB

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