RSA Cipher Encryption



In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation.

The modules included for the encryption algorithm are as follows −

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
def generate_keys():
   privatekey = rsa.generate_private_key(public_exponent=65537, key_size=2048)
   publickey = privatekey.public_key()
   return privatekey, publickey

For encryption, the following function is used which follows the RSA algorithm −

def encrypt_message(message , publickey):
   return publickey.encrypt(message,
      padding.OAEP(
         mgf=padding.MGF1(algorithm=hashes.SHA256()),
         algorithm=hashes.SHA256(),
         label=None
      ))

Two parameters are mandatory: message and publickey which refers to Public key. A public key is used for encryption and private key is used for decryption.

The complete program for encryption procedure is mentioned below −

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes

def generate_keys():
   privatekey = rsa.generate_private_key(public_exponent=65537, key_size=2048)
   publickey = privatekey.public_key()
   return privatekey, publickey

def encrypt_message(a_message , publickey):
   return publickey.encrypt(a_message,
      padding.OAEP(
         mgf=padding.MGF1(algorithm=hashes.SHA256()),
         algorithm=hashes.SHA256(),
         label=None
      ))
Advertisements