Pure Python RSA implementation
Python-RSA is a pure-Python RSA implementation. It supports encryption and decryption, signing and verifying signatures, and key generation according to PKCS#1 version 1.5. It can be used as a Python library as well as on the commandline. The code was mostly written by Sybren A. Stüvel.
Documentation can be found at the Python-RSA homepage. For all changes, check the changelog.
Download and install using:
or download it from the Python Package Index.
The source code is maintained at GitHub and is licensed under the Apache License, version 2.0
Security
Because of how Python internally stores numbers, it is very hard (if not impossible) to make a pure-Python program secure against timing attacks. This library is no exception, so use it with care. See https://securitypitfalls.wordpress.com/2018/08/03/constant-time-compare-in-python/ for more info.
Setup of Development Environment
Publishing a New Release
Since this project is considered critical on the Python Package Index, two-factor authentication is required. For uploading packages to PyPi, an API key is required; username+password will not work.
First, generate an API token at https://pypi.org/manage/account/token/. Then, use this token when publishing instead of your username and password.
As username, use __token__ . As password, use the token itself, including the pypi- prefix.
See https://pypi.org/help/#apitoken for help using API tokens to publish. This is what I have in
The pip install twine is necessary as Python-RSA requires Python >= 3.6, and Twine requires at least version 3.7. This means Poetry refuses to add it as dependency.
Name already in use
python-rsa / doc / installation.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Installation can be done in various ways. The simplest form uses pip:
Depending on your system you may need to use sudo pip if you want to install the library system-wide, or use pip install —user rsa to install the library in your home directory.
Installation from source is also quite easy. Download the source and then type:
The sources are tracked in our Git repository at GitHub. It also hosts the issue tracker.
Python-RSA is compatible with Python versions 3.5 and newer. The last version with Python 2.7 support was Python-RSA 4.0.
Python-RSA has very few dependencies. As a matter of fact, to use it you only need Python itself. Loading and saving keys does require an extra module, though: pyasn1. If you used pip or easy_install like described above, you should be ready to go.
In order to start developing on Python-RSA, use Git to get a copy of the source:
Use Pipenv to install the development requirements in a virtual environment:
RSA with Cryptography Python Library
Cryptography python library was born with the goal of being the “cryptographic standard library”.
Welcome to pyca/cryptography — Cryptography 2.0.dev1 documentation
cryptography includes both high level recipes and low level interfaces to common cryptographic algorithms such as…
pyca/cryptography
cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.
There are Python libraries that provide cryptography services: M2Crypto, PyCrypto, pyOpenSSL, python-nss, and Botan’s Python bindings. Five criteria can be evaluated when you try to select one of them: which C backend, how well maintained, Python support, reviewed and completeness. All failed the “reviewed” category. e.g. PyCrypto (probably the most used cryptographic library for Python) don’t work on PyPy.
The hope behind this new library is that it will become the cryptographic standard for Python. It will incorporate modern algorithms (e.g. AES-GCM and forward security) that have been “important for a long time” but have been ignored in alternative libraries. Cryptography will be thoroughly tested and come with “sane defaults” and a “sane API”. It will support Python 2.x, Python 3.x, and PyPy. It will be well-maintained and, unlike most of the alternatives, will not have known broken options.
Cryptography core developers set out to design a better library, with the following principles:
- It should never be easier to do the wrong thing than it is to do the right thing.
- You shouldn’t need to be a cryptography expert to use it, the documentation should equip you to make the right decisions.
- Things which are dangerous should be obviously dangerous, not subtly dangerous.
- Put our users’ safety and security above all else.
Now, We are going to play a little bit with this library and specially with RSA asymmetric algorithm. I’m building a pet project related with security where I’m using this asymmetric algorithm.
Firstly, you can install Cryptography with pip:
For Debian and Ubuntu, the following command will ensure that the required dependencies are installed:
You should to ensure OpenSSl and libssl are the latest versions as well.
You can obtain the complete installation instructions here:
Installation — Cryptography 2.0.dev1 documentation
As of OpenSSL 1.1.0 the library names have changed from and to and (matching their names on all other platforms)…
When implementing the flow of sending messages, you’ll need to follow careful cryptographic procedures to ensure everything will work properly.
If Maria wants to send a secret message to me, she needs to follow the next flow:
- Maria and Raul must have their RSA key pair with private and public key.
2. Firstly she should encrypts her message with the Raul’s public key to send it encrypted.
O AEP es the recommended padding choice for encryption for new protocols or applications. PKCS1v15 should only be used to support legacy protocols.
3. If you already have a RSA public key in the PEM format (which are recognizable by the distinctive -BEGIN
4. Next Maria should signs your message with her private key to ensure the recipient can check the message sender with Maria’s public key to verify the sender identity.
PSS algorithm is the recommended padding choice for any new protocols or applications, PKCS1v15 should only be used to support legacy protocols.
5. Maria has everything she needs to send her secret message to me now:
6. When I receive Maria’s message the first thing I have to do to decrypt the message is:
7. Last resort, I should check the message origin to determine the identity of message emisor:
Finally, I have got in my power the secret message sent by Maria and I’ve can check the message is authentic. I’m not able to hide my joy!
The goal was to show a small example with the criptography python library and RSA algorithm. With this example, we can create a small handler class to manage encrypted content.
If you are interested in learning more about the field of cryptography and Python, I recommend:
Как установить rsa в python
RSA is the most widespread and used public key algorithm. Its security is based on the difficulty of factoring large integers. The algorithm has withstood attacks for more than 30 years, and it is therefore considered reasonably secure for new designs.
The algorithm can be used for both confidentiality (encryption) and authentication (digital signature). It is worth noting that signing and decryption are significantly slower than verification and encryption.
The cryptographic strength is primarily linked to the length of the RSA modulus n. In 2017, a sufficient length is deemed to be 2048 bits. For more information, see the most recent ECRYPT report.
Both RSA ciphertexts and RSA signatures are as large as the RSA modulus n (256 bytes if n is 2048 bit long).
The module Crypto.PublicKey.RSA provides facilities for generating new RSA keys, reconstructing them from known components, exporting them, and importing them.
As an example, this is how you generate a new RSA key pair, save it in a file called mykey.pem , and then read it back:
Create a new RSA key pair.
The algorithm closely follows NIST FIPS 186-4 in its sections B.3.1 and B.3.3. The modulus is the product of two non-strong probable primes. Each prime passes a suitable number of Miller-Rabin tests with random bases and a single Lucas test.
- bits (integer) – Key length, or size (in bits) of the RSA modulus. It must be at least 1024, but 2048 is recommended. The FIPS standard only defines 1024, 2048 and 3072.
- randfunc (callable) – Function that returns random bytes. The default is Crypto.Random.get_random_bytes() .
- e (integer) – Public RSA exponent. It must be an odd positive integer. It is typically a small number with very few ones in its binary representation. The FIPS standard requires the public exponent to be at least 65537 (the default).
Returns: an RSA key object ( RsaKey , with private key).
Crypto.PublicKey.RSA. construct ( rsa_components, consistency_check=True ) ¶
Construct an RSA key from a tuple of valid RSA components.
The modulus n must be the product of two primes. The public exponent e must be odd and larger than 1.
In case of a private key, the following equations must apply:
A tuple of integers, with at least 2 and no more than 6 items. The items come in the following order:
- RSA modulus n.
- Public exponent e.
- Private exponent d. Only required if the key is private.
- First factor of n (p). Optional, but the other factor q must also be present.
- Second factor of n (q). Optional.
- CRT coefficient q, that is \(p^ <-1>\text
q\) . Optional.
ValueError – when the key being imported fails the most basic RSA validity checks.
Returns: An RSA key object ( RsaKey ).
Crypto.PublicKey.RSA. import_key ( extern_key, passphrase=None ) ¶
Import an RSA key (public or private).
The RSA key to import.
The following formats are supported for an RSA public key:
- X.509 certificate (binary or PEM format)
- X.509 subjectPublicKeyInfo DER SEQUENCE (binary or PEM encoding) RSAPublicKey DER SEQUENCE (binary or PEM encoding)
- An OpenSSH line (e.g. the content of
The following formats are supported for an RSA private key:
- PKCS#1 RSAPrivateKey DER SEQUENCE (binary or PEM encoding) PrivateKeyInfo or EncryptedPrivateKeyInfo DER SEQUENCE (binary or PEM encoding)
- OpenSSH (text format, introduced in OpenSSH 6.5)
For details about the PEM encoding, see RFC1421/RFC1423.
Returns: An RSA key object ( RsaKey ).
Raises: | ValueError/IndexError/TypeError – When the given key cannot be parsed (possibly because the pass phrase is wrong). |
---|
class Crypto.PublicKey.RSA. RsaKey ( **kwargs ) ¶
Class defining an actual RSA key. Do not instantiate directly. Use generate() , construct() or import_key() instead.
- n (integer) – RSA modulus
- e (integer) – RSA public exponent
- d (integer) – RSA private exponent
- p (integer) – First factor of the RSA modulus
- q (integer) – Second factor of the RSA modulus
- invp (integer) – Chinese remainder component ( \(p^ <-1>\text
q\) ) - invq (integer) – Chinese remainder component ( \(q^ <-1>\text
p\) ) - u (integer) – Same as invp
Export this RSA key.
The format to use for wrapping the key:
- ’PEM’. (Default) Text encoding, done according to RFC1421/RFC1423.
- ’DER’. Binary encoding.
- ’OpenSSH’. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys).
(For private keys only) The ASN.1 structure to use for serializing the key. Note that even in case of PEM encoding, there is an inner ASN.1 DER structure.
With pkcs=1 (default), the private key is encoded in a simple PKCS#1 structure ( RSAPrivateKey ).
With pkcs=8 , the private key is encoded in a PKCS#8 structure ( PrivateKeyInfo ).
This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER SubjectPublicKeyInfo structure is always used.
(For private keys only) The encryption scheme to use for protecting the private key.
If None (default), the behavior depends on format :
-
For ‘DER’, the PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC scheme is used. The following operations are performed:
- A 16 byte Triple DES key is derived from the passphrase using Crypto.Protocol.KDF.PBKDF2() with 8 bytes salt, and 1 000 iterations of Crypto.Hash.HMAC .
- The private key is encrypted using CBC.
- The encrypted key is encoded according to PKCS#8.
Specifying a value for protection is only meaningful for PKCS#8 (that is, pkcs=8 ) and only if a pass phrase is present too.
The supported schemes for PKCS#8 are listed in the Crypto.IO.PKCS8 module (see wrap_algo parameter).
the encoded key
ValueError – when the format is unknown or when you try to encrypt a private key with DER format and PKCS#1.
If you don’t provide a pass phrase, the private key will be exported in the clear!
Export this RSA key.
The format to use for wrapping the key:
- ’PEM’. (Default) Text encoding, done according to RFC1421/RFC1423.
- ’DER’. Binary encoding.
- ’OpenSSH’. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys).
(For private keys only) The ASN.1 structure to use for serializing the key. Note that even in case of PEM encoding, there is an inner ASN.1 DER structure.
With pkcs=1 (default), the private key is encoded in a simple PKCS#1 structure ( RSAPrivateKey ).
With pkcs=8 , the private key is encoded in a PKCS#8 structure ( PrivateKeyInfo ).
This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER SubjectPublicKeyInfo structure is always used.
(For private keys only) The encryption scheme to use for protecting the private key.
If None (default), the behavior depends on format :
-
For ‘DER’, the PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC scheme is used. The following operations are performed:
- A 16 byte Triple DES key is derived from the passphrase using Crypto.Protocol.KDF.PBKDF2() with 8 bytes salt, and 1 000 iterations of Crypto.Hash.HMAC .
- The private key is encrypted using CBC.
- The encrypted key is encoded according to PKCS#8.
Specifying a value for protection is only meaningful for PKCS#8 (that is, pkcs=8 ) and only if a pass phrase is present too.
The supported schemes for PKCS#8 are listed in the Crypto.IO.PKCS8 module (see wrap_algo parameter).
the encoded key
ValueError – when the format is unknown or when you try to encrypt a private key with DER format and PKCS#1.
If you don’t provide a pass phrase, the private key will be exported in the clear!
Whether this is an RSA private key
A matching RSA public key.
Returns: | a new RsaKey object |
---|
publickey ( ) ¶
A matching RSA public key.
Returns: | a new RsaKey object |
---|
size_in_bits ( ) ¶
Size of the RSA modulus in bits
The minimal amount of bytes that can hold the RSA modulus
Crypto.PublicKey.RSA. oid = ‘1.2.840.113549.1.1.1’¶
Object ID for the RSA encryption algorithm. This OID often indicates a generic RSA key, even when such key will be actually used for digital signatures.