5. Usage — Python-RSA 4.8 documentation (2024)

This section describes the usage of the Python-RSA module.

Before you can use RSA you need keys. You will receive a private keyand a public key.

Important

The private key is called private for a reason. Never share thiskey with anyone.

The public key is used for encrypting a message such that it can onlybe read by the owner of the private key. As such it’s also referred toas the encryption key. Decrypting a message can only be done usingthe private key, hence it’s also called the decryption key.

The private key is used for signing a message. With this signature andthe public key, the receiver can verify that a message was signedby the owner of the private key, and that the message was not modifiedafter signing.

5.1. Generating keys

You can use the rsa.newkeys() function to create a key pair:

>>> import rsa>>> (pubkey, privkey) = rsa.newkeys(512)

Alternatively you can use rsa.PrivateKey.load_pkcs1() andrsa.PublicKey.load_pkcs1() to load keys from a file:

>>> import rsa>>> with open('private.pem', mode='rb') as privatefile:...  keydata = privatefile.read()>>> privkey = rsa.PrivateKey.load_pkcs1(keydata)

5.1.1. Time to generate a key

Generating a key pair may take a long time, depending on the number ofbits required. The number of bits determines the cryptographicstrength of the key, as well as the size of the message you canencrypt. If you don’t mind having a slightly smaller key than yourequested, you can pass accurate=False to speed up the keygeneration process.

Another way to speed up the key generation process is to use multipleprocesses in parallel to speed up the key generation. Use no more thanthe number of processes that your machine can run in parallel; adual-core machine should use poolsize=2; a quad-corehyperthreading machine can run two threads on each core, and thus canuse poolsize=8.

>>> (pubkey, privkey) = rsa.newkeys(512, poolsize=8)

These are some average timings from my desktop machine (Linux 2.6,2.93 GHz quad-core Intel Core i7, 16 GB RAM) using 64-bit CPython 2.7.Since key generation is a random process, times may differ even onsimilar hardware. On all tests, we used the default accurate=True.

Keysize (bits)

single process

eight processes

128

0.01 sec.

0.01 sec.

256

0.03 sec.

0.02 sec.

384

0.09 sec.

0.04 sec.

512

0.11 sec.

0.07 sec.

1024

0.79 sec.

0.30 sec.

2048

6.55 sec.

1.60 sec.

3072

23.4 sec.

7.14 sec.

4096

72.0 sec.

24.4 sec.

If key generation is too slow for you, you could use OpenSSL togenerate them for you, then load them in your Python code. OpenSSLgenerates a 4096-bit key in 3.5 seconds on the same machine as usedabove. See Interoperability with OpenSSL for more information.

5.2. Encryption and decryption

To encrypt or decrypt a message, use rsa.encrypt() resp.rsa.decrypt(). Let’s say that Alice wants to send a messagethat only Bob can read.

  1. Bob generates a key pair, and gives the public key to Alice. This isdone such that Alice knows for sure that the key is really Bob’s(for example by handing over a USB stick that contains the key).

    >>> import rsa>>> (bob_pub, bob_priv) = rsa.newkeys(512)
  2. Alice writes a message, and encodes it in UTF-8. The RSA moduleonly operates on bytes, and not on strings, so this step isnecessary.

    >>> message = 'hello Bob!'.encode('utf8')
  3. Alice encrypts the message using Bob’s public key, and sends theencrypted message.

    >>> import rsa>>> crypto = rsa.encrypt(message, bob_pub)
  4. Bob receives the message, and decrypts it with his private key.

    >>> message = rsa.decrypt(crypto, bob_priv)>>> print(message.decode('utf8'))hello Bob!

Since Bob kept his private key private, Alice can be sure that he isthe only one who can read the message. Bob does not know for surethat it was Alice that sent the message, since she didn’t sign it.

RSA can only encrypt messages that are smaller than the key. A coupleof bytes are lost on random padding, and the rest is available for themessage itself. For example, a 512-bit key can encode a 53-bytemessage (512 bit = 64 bytes, 11 bytes are used for random padding andother stuff). See Working with big files for information on how to work withlarger files.

Altering the encrypted information will likely cause arsa.pkcs1.DecryptionError. If you want to be sure, usersa.sign().

>>> crypto = rsa.encrypt(b'hello', bob_pub)>>> crypto = crypto[:-1] + b'X' # change the last byte>>> rsa.decrypt(crypto, bob_priv)Traceback (most recent call last):...rsa.pkcs1.DecryptionError: Decryption failed

Warning

Never display the stack trace of arsa.pkcs1.DecryptionError exception. It shows wherein the code the exception occurred, and thus leaks informationabout the key. It’s only a tiny bit of information, but every bitmakes cracking the keys easier.

5.2.1. Low-level operations

The core RSA algorithm operates on large integers. These operationsare considered low-level and are supported by thersa.core.encrypt_int() and rsa.core.decrypt_int()functions.

5.3. Signing and verification

You can create a detached signature for a message using thersa.sign() function:

>>> (pubkey, privkey) = rsa.newkeys(512)>>> message = 'Go left at the blue tree'.encode()>>> signature = rsa.sign(message, privkey, 'SHA-1')

This hashes the message using SHA-1. Other hash methods are alsopossible, check the rsa.sign() function documentation fordetails. The hash is then signed with the private key.

It is possible to calculate the hash and signature in separate operations(i.e for generating the hash on a client machine and then sign with aprivate key on remote server). To hash a message use the rsa.compute_hash()function and then use the rsa.sign_hash() function to sign the hash:

>>> message = 'Go left at the blue tree'.encode()>>> hash = rsa.compute_hash(message, 'SHA-1')>>> signature = rsa.sign_hash(hash, privkey, 'SHA-1')

In order to verify the signature, use the rsa.verify()function. If the verification is successful, this function returnsthe hash algorithm used as a string:

>>> message = 'Go left at the blue tree'.encode()>>> rsa.verify(message, signature, pubkey)'SHA-1'

Modify the message, and the signature is no longer valid and arsa.pkcs1.VerificationError is thrown:

>>> message = 'Go right at the blue tree'.encode()>>> rsa.verify(message, signature, pubkey)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/sybren/workspace/python-rsa/rsa/pkcs1.py", line 289, in verify raise VerificationError('Verification failed')rsa.pkcs1.VerificationError: Verification failed

Warning

Never display the stack trace of arsa.pkcs1.VerificationError exception. It shows wherein the code the exception occurred, and thus leaks informationabout the key. It’s only a tiny bit of information, but every bitmakes cracking the keys easier.

Instead of a message you can also call rsa.sign() andrsa.verify() with a file-like object. If themessage object has a read(int) method it is assumed to be a file.In that case the file is hashed in 1024-byte blocks at the time.

>>> with open('somefile', 'rb') as msgfile:...  signature = rsa.sign(msgfile, privkey, 'SHA-1')
>>> with open('somefile', 'rb') as msgfile:...  rsa.verify(msgfile, signature, pubkey)

5.4. Working with big files

RSA can only encrypt messages that are smaller than the key. A coupleof bytes are lost on random padding, and the rest is available for themessage itself. For example, a 512-bit key can encode a 53-bytemessage (512 bit = 64 bytes, 11 bytes are used for random padding andother stuff).

5.4.1. How it usually works

The most common way to use RSA with larger files uses a block cypherlike AES or DES3 to encrypt the file with a random key, then encryptthe random key with RSA. You would send the encrypted file along withthe encrypted key to the recipient. The complete flow is:

  1. Generate a random key

    >>> import rsa.randnum>>> aes_key = rsa.randnum.read_random_bits(128)
  2. Use that key to encrypt the file with AES.

  3. Encrypt the AES key with RSA

    >>> encrypted_aes_key = rsa.encrypt(aes_key, public_rsa_key)
  4. Send the encrypted file together with encrypted_aes_key

  5. The recipient now reverses this process to obtain the encryptedfile.

Note

The Python-RSA module does not contain functionality to do the AESencryption for you.

5.4.2. Only using Python-RSA: the VARBLOCK format

Warning

The VARBLOCK format is NOT recommended for general use, has been deprecated sincePython-RSA 3.4, and has been removed in version 4.0. It’s vulnerable to anumber of attacks:

  1. decrypt/encrypt_bigfile() does not implement Authenticated encryption noruses MACs to verify messages before decrypting public key encrypted messages.

  2. decrypt/encrypt_bigfile() does not use hybrid encryption (it uses plain RSA)and has no method for chaining, so block reordering is possible.

See issue #19 on GitHub for more information.

As of Python-RSA version 4.0, the VARBLOCK format has been removed from thelibrary. For now, this section is kept here to document the issues with thatformat, and ensure we don’t do something like that again.

5. Usage — Python-RSA 4.8 documentation (2024)

FAQs

5. Usage — Python-RSA 4.8 documentation? ›

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. The sources are tracked in our Git repository at GitHub.

How to install RSA package in Python? ›

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. The sources are tracked in our Git repository at GitHub.

What is the key size of RSA in Python? ›

Key Size — Key size or called key lengh is how many bits of a RSA key. It could be 1024, 2048, 3072, 4096, 8129, 16384, or even more bits. The longer key, the more time during key generation, as well as computation time for encryption and decryption. Currently, key size of 3072-bits or more are considered secure.

What is RSA used for? ›

The RSA algorithm (Rivest-Shamir-Adleman) is the basis of a cryptosystem -- a suite of cryptographic algorithms that are used for specific security services or purposes -- which enables public key encryption and is widely used to secure sensitive data, particularly when it is being sent over an insecure network such as ...

How to use RSA in Python? ›

The complete flow is:
  1. Generate a random key. >>> import rsa.randnum >>> aes_key = rsa. randnum. ...
  2. Use that key to encrypt the file with AES.
  3. Encrypt the AES key with RSA. >>> encrypted_aes_key = rsa. ...
  4. Send the encrypted file together with encrypted_aes_key.
  5. The recipient now reverses this process to obtain the encrypted file.

How to generate RSA key command? ›

Generate RSA Keys
  1. Open a shell using Putty or another utility.
  2. Use commands to generate an RSA key file. Type the following command to generate RSA keys: ssh-keygen -t rsa. ...
  3. Navigate to the. rsakey. folder that you created in step 2b. ...
  4. Locate the public key beginning with. ssh. and copy the key.

How to solve RSA algorithm example? ›

RSA Algorithm Example
  1. Choose p = 3 and q = 11.
  2. Compute n = p * q = 3 * 11 = 33.
  3. Compute φ(n) = (p - 1) * (q - 1) = 2 * 10 = 20.
  4. Choose e such that 1 < e < φ(n) and e and φ (n) are coprime. ...
  5. Compute a value for d such that (d * e) % φ(n) = 1. ...
  6. Public key is (e, n) => (7, 33)
  7. Private key is (d, n) => (3, 33)

How to implement RSA key? ›

Windows Users
  1. Start the PuTTYgen utility, by double-clicking on its .exe file.
  2. For Type of key to generate, select RSA.
  3. In the Number of bits in a generated key field, specify either 2048 or 4096 (increasing the bits makes it harder to crack the key by brute-force methods. ...
  4. Click the Generate button.
Mar 1, 2024

How does RSA code work? ›

The RSA SecurID authentication mechanism consists of a "token"—either hardware (e.g. a key fob) or software (a soft token)—which is assigned to a computer user and which creates an authentication code at fixed intervals (usually 60 seconds) using a built-in clock and the card's factory-encoded almost random key (known ...

How is RSA used now? ›

More often, RSA is used to transmit shared keys for symmetric-key cryptography, which are then used for bulk encryption–decryption.

Where is RSA key used? ›

RSA key is a private key based on RSA algorithm. Private Key is used for authentication and a symmetric key exchange during establishment of an SSL/TLS session. It is a part of the public key infrastructure that is generally used in case of SSL certificates.

How to encrypt text using the RSA algorithm? ›

Steps in RSA Algorithm
  1. Choose two large prime numbers (p and q)
  2. Calculate n = p*q and z = (p-1)(q-1)
  3. Choose a number e where 1 < e < z.
  4. Calculate d = e-1mod(p-1)(q-1)
  5. You can bundle private key pair as (n,d)
  6. You can bundle public key pair as (n,e)
Jul 2, 2024

How do I install RSA app? ›

  1. Step 1: Choose your token.
  2. Step 2: Install the software. The SecurID software is what you'll use to generate your unique passcode to help verify your identity. ...
  3. Step 2: Install the software. ...
  4. Step 3: Import your token. ...
  5. Step 3: Import your token.

How to install RSA key? ›

To perform a silent installation, perform the following steps. Right-click the command prompt icon from the Start menu and click Run as administrator to open the command prompt. Navigate to the directory that contains the RSA Security Key Utility x64. msi or RSA Security Key Utility x86.

How to install RSA certificate? ›

  1. In the Operations Console, click Deployment Configuration > Certificates > Console Certificate Management. ...
  2. In the Console Certificate Management page, click Import Certificate.
  3. In the Import Certificate page under Certificate Basics, do one of the following: ...
  4. Click Import.

How to install operator package in Python? ›

Installation
  1. To install the latest version of operator-courier, just install the latest release from PyPI: $ pip3 install operator-courier.
  2. To install a specific release, use the == operator and specify the version. ...
  3. To upgrade an existing operator-courier release: $ pip3 install -U operator-courier.

Top Articles
Stochastic RSI (StochRSI) Definition, Examples, and Real-World Uses
Ancient Crete
What Is Single Sign-on (SSO)? Meaning and How It Works? | Fortinet
Hotels
Jennifer Hart Facebook
Coindraw App
Teamexpress Login
Tanger Outlets Sevierville Directory Map
Kostenlose Games: Die besten Free to play Spiele 2024 - Update mit einem legendären Shooter
Mndot Road Closures
Dityship
Immediate Action Pathfinder
Slushy Beer Strain
Hca Florida Middleburg Emergency Reviews
Viprow Golf
Youravon Comcom
Dutch Bros San Angelo Tx
Eva Mastromatteo Erie Pa
Abortion Bans Have Delayed Emergency Medical Care. In Georgia, Experts Say This Mother’s Death Was Preventable.
Brett Cooper Wikifeet
Swedestats
Uky Linkblue Login
Average Salary in Philippines in 2024 - Timeular
Georgetown 10 Day Weather
Reptile Expo Fayetteville Nc
27 Paul Rudd Memes to Get You Through the Week
11 Ways to Sell a Car on Craigslist - wikiHow
Bellin Patient Portal
Lacey Costco Gas Price
Leben in Japan &#8211; das muss man wissen - Lernen Sie Sprachen online bei italki
The Creator Showtimes Near Baxter Avenue Theatres
Perry Inhofe Mansion
Memberweb Bw
Http://N14.Ultipro.com
Bimmerpost version for Porsche forum?
Vision Source: Premier Network of Independent Optometrists
Devotion Showtimes Near The Grand 16 - Pier Park
Albertville Memorial Funeral Home Obituaries
Lake Andes Buy Sell Trade
Carroll White Remc Outage Map
Kb Home The Overlook At Medio Creek
Rs3 Nature Spirit Quick Guide
Portal Pacjenta LUX MED
Fatal Accident In Nashville Tn Today
Stosh's Kolaches Photos
Holzer Athena Portal
Ts In Baton Rouge
Canvas Elms Umd
Causeway Gomovies
Verilife Williamsport Reviews
Read Love in Orbit - Chapter 2 - Page 974 | MangaBuddy
Cognitive Function Test Potomac Falls
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 5785

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.