Creating RSA Keys with Python



In this article we are going to discuss how to create RSA keys. RSA is a well known encryption algorithm used for securing data. It is based on two keys: a public key and a private key. The public key is used for encryption, and the private key is used for decryption.

RSA keys are created using a mathematical process that utilizes large prime numbers. To generate an RSA key, two large prime numbers are chosen and multiplied together. This product forms the modulus for both public and private RSA keys. The security of RSA depends on the difficulty of breaking down the modulus into its original prime factors, especially if the numbers used are extremely large.

Public and Private Keys

RSA, a cryptography method, uses a pair of keys: a publicly shared public key for encrypting messages and a secret private key for decrypting them. The private key must remain confidential and accessible only to its owner.

Encryption and Decryption

When sending a message securely, the sender uses the receiver's publicly available key to encode it.

To unlock the encrypted message, the receiver needs to use their secret private key.

This distinctive encryption system guarantees that even if the encoded message is intercepted along with the public key, it remains secure since the private key is not accessible to unauthorized persons.

Key Generation Steps

RSA need a multiplicative group G =< ZΦn,*, X > for key generation. This group provides only multiplication and divisions, which are required for generation of public and private keys. This group is secret from the public because its modulus, Φ(n) is hidden from the public.

The public and the private key-generation algorithm is the most difficult element of RSA cryptography. There are two large prime numbers, p and q, are produced using the Rabin-Miller primarily test algorithm.

A modulus n is computed by multiplying p and q. This number can be used by both the public and private keys and supports the connection between them. Its length, generally defined in bits, is known as key length.

The public key includes the modulus n, and a public exponent, e, which is usually set at 65537, as it's a prime number that is not too big. The e figure doesn't have to be a privately chosen prime number as the public key is shared with everyone.

The private key includes the modulus n and the private exponent d, which is computed using the Extended Euclidean algorithm to discover the multiplicative inverse regarding the totient of n.

Considering arithmetic modulo n, let us say that e is an integer that is co-prime to the totient Φ(n) of n. Moreover, it can say that d is the multiplicative inverse of e modulo Φ (n). These definitions of the several symbols are listed below for convenience −

  • n = a modulus for modular arithmetic
  • Φ (n) = the totient of n
  • e = an integer that is associatively prime to Φ(n)
  • [T his guarantees that e will possess a multiplicative inverse modulo Φ(n)]
  • d = an integer that is the multiplicative inverse of e modulo Φ(n)

The computational steps for key generation are −

  • Generate two different primes including p and q.
  • Compute the modulus n = p x q
  • Compute the totient Φ(n) = (p - 1) x (q - 1)
  • Select for public exponent an integer e such that 1 < e <Φ(n) and gcd(Φ(n), e) = 1.
  • Compute for the private exponent a value for d such that d = e-1 mod Φ(n)
  • Public Key = [e, n]
  • Private Key = [d, n]

Installing Required Libraries

First make sure you have Python installed on your system. Then, launch the terminal or command prompt and install the cryptography library utilizing the "pip" package installer −

pip install cryptography

Generation of RSA Keys

In this python program we will create RSA keys, which are useful for secure message encryption and decryption. Necessary modules for key generation are first imported. It then generates a new RSA key pair with a private key and a public key (2048 bits). The private key is saved in PEM format, a widely used encrypted key encoding standard. The public key is saved in PEM format with the appropriate formatting. Finally, the keys are saved as 'private_key.pem' and 'public_key.pem'. This code is important for creating secure communication channels where data protection is necessary.

For creating the keys you need to open your favorite text editor or Python IDE. Create a new Python script and name it something like rsa_key_generation.py. Then you need to copy and paste the below code into your script −

Example

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

# create a new RSA key pair
private_key = rsa.generate_private_key(
   public_exponent=65537,
   key_size=2048,
   backend=default_backend()
)

# get the public key from the private key
public_key = private_key.public_key()

# the private key to PEM format
private_key_pem = private_key.private_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PrivateFormat.PKCS8,
   encryption_algorithm=serialization.NoEncryption()
)

# the public key to PEM format
public_key_pem = public_key.public_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# save the keys to files
with open('private_key.pem', 'wb') as f:
   f.write(private_key_pem)
with open('public_key.pem', 'wb') as f:
   f.write(public_key_pem)
print("RSA keys have been generated successfully!")

Run the Code

  • Save your Python program.
  • Open a terminal or command prompt.
  • Navigate to the directory where your code is saved.

Run the script by typing −

python rsa_key_generation.py

Output

When you run the program, you will see two files in your specific directory where your program is saved. And the file names will be private_key.pem and public_key.pem.

These files will have your private and public keys, respectively, in PEM format.

PEM(Privacy Enhanced Mail) files are a standard digital security format used for storing cryptographic keys and certificates within the PKI framework. Originally designed to enhance email security, PEM has evolved into a widely accepted standard for various online security applications.

RSA keys have been generated successfully!
RSA keys implementation

That's it! We have successfully created RSA keys with the help of the cryptography package of Python. You can now use these keys for encryption and decryption purposes in your applications.

Limitations and Considerations

There are some limitations and considerations you should know about RSA Keys −

  • RSA encryption and decryption can take a lot of processing power, especially with longer keys.
  • As computers get more powerful, we may need to use longer keys to keep things secure.
  • RSA has some weaknesses that attackers can use, like trying to factor large numbers or using certain encrypted messages. These weaknesses should be kept in mind when using RSA for security purposes.

Summary

In this chapter, we explored how we can create RSA encryption keys using Python. RSA involves using a pair of keys: a publicly available key for encrypting data, and a private key for decrypting it. These RSA keys are generated using large prime numbers, making them challenging to crack. We created a key pair with a private key and corresponding public key. We also gained insights into installing Python libraries and coding RSA key generation. Finally, we learned about running the code and saving the generated keys as files. This understanding helps us to develop secure communication systems that safeguard data from unauthorized access.

Advertisements