English 中文(简体)
RSA Cipher Encryption
  • 时间:2024-12-22

RSA Cipher Encryption


Previous Page Next Page  

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 Crypto.PubpcKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

We have initiapzed the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of pubpc and private key using the following code.

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, pubpc = key, key.pubpckey()
   return pubpc, private
def importKey(externKey):
   return RSA.importKey(externKey)

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

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

Two parameters are mandatory: message and pub_key which refers to Pubpc key. A pubpc key is used for encryption and private key is used for decryption.

The complete program for encryption procedure is mentioned below −

from Crypto.PubpcKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, pubpc = key, key.pubpckey()
   return pubpc, private

def importKey(externKey):
   return RSA.importKey(externKey)

def getpubpckey(priv_key):
   return priv_key.pubpckey()

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)
Advertisements