| 1 |
RSA |
| 2 |
=== |
| 3 |
|
| 4 |
RSA_ is one of the most widespread and public key algorithms. Its security is |
| 5 |
based on the difficulty of factoring large integers. The algorithm has |
| 6 |
withstood attacks for more than 30 years, and it is therefore considered |
| 7 |
reasonably secure. |
| 8 |
|
| 9 |
However, for new designs, it is recommended to use :doc:`ECC <ecc>`, |
| 10 |
because keys are smaller and private key operations are faster. |
| 11 |
|
| 12 |
The RSA algorithm can be used for both confidentiality (encryption) and |
| 13 |
authentication (digital signature). Signing and |
| 14 |
decryption are significantly slower than verification and encryption. |
| 15 |
|
| 16 |
The cryptographic strength is primarily linked to the length of the RSA modulus *n*. |
| 17 |
In 2023, a sufficient length is deemed to be 3072 bits. For more information, |
| 18 |
see the most recent NIST_ report. |
| 19 |
Both RSA ciphertexts and RSA signatures are as large as the RSA modulus *n* (384 |
| 20 |
bytes if *n* is 3072 bit long). |
| 21 |
|
| 22 |
With this module you can generate new RSA keys:: |
| 23 |
|
| 24 |
>>> from Crypto.PublicKey import RSA |
| 25 |
>>> |
| 26 |
>>> mykey = RSA.generate(3072) |
| 27 |
|
| 28 |
export an RSA private key and protect it with a password, so that it is |
| 29 |
resistant to brute force attacks:: |
| 30 |
|
| 31 |
>>> pwd = b'secret' |
| 32 |
>>> with open("myprivatekey.pem", "wb") as f: |
| 33 |
>>> data = mykey.export_key(passphrase=pwd, |
| 34 |
pkcs=8, |
| 35 |
protection='PBKDF2WithHMAC-SHA512AndAES256-CBC', |
| 36 |
prot_params={'iteration_count':131072}) |
| 37 |
>>> f.write(data) |
| 38 |
|
| 39 |
and reimport it later:: |
| 40 |
|
| 41 |
>>> pwd = b'secret' |
| 42 |
>>> with open("myprivatekey.pem", "rb") as f: |
| 43 |
>>> data = f.read() |
| 44 |
>>> mykey = RSA.import_key(data, pwd) |
| 45 |
|
| 46 |
You can also export the public key, which is not sensitive:: |
| 47 |
|
| 48 |
>>> with open("mypublickey.pem", "wb") as f: |
| 49 |
>>> data = mykey.public_key().export_key() |
| 50 |
|
| 51 |
For signing data with RSA, use a higher level module such as :ref:`rsa_pss`. |
| 52 |
|
| 53 |
For encrypting data with RSA, use :ref:`rsa_oaep`. |
| 54 |
|
| 55 |
.. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29 |
| 56 |
.. _NIST: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf |
| 57 |
|
| 58 |
.. automodule:: Crypto.PublicKey.RSA |
| 59 |
:members: |