Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

asymmetric encryption python

#RSA_cryptography.py
#Importing necessary modules
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from binascii import hexlify
#The message to be encrypted
message = b'Public and Private keys encryption'
#Generating private key (RsaKey object) of key length of 1024 bits
private_key = RSA.generate(1024)
#Generating the public key (RsaKey object) from the private key
public_key = private_key.publickey()
print(type(private_key), type(public_key))
#Converting the RsaKey objects to string 
private_pem = private_key.export_key().decode()
public_pem = public_key.export_key().decode()
print(type(private_pem), type(public_pem))
#Writing down the private and public keys to 'pem' files
with open('private_pem.pem', 'w') as pr:
    pr.write(private_pem)
with open('public_pem.pem', 'w') as pu:
    pu.write(public_pem)
    
#Importing keys from files, converting it into the RsaKey object   
pr_key = RSA.import_key(open('private_pem.pem', 'r').read())
pu_key = RSA.import_key(open('public_pem.pem', 'r').read())
print(type(pr_key), type(pu_key))
#Instantiating PKCS1_OAEP object with the public key for encryption
cipher = PKCS1_OAEP.new(key=pu_key)
#Encrypting the message with the PKCS1_OAEP object
cipher_text = cipher.encrypt(message)
print(cipher_text)
#Instantiating PKCS1_OAEP object with the private key for decryption
decrypt = PKCS1_OAEP.new(key=pr_key)
#Decrypting the message with the PKCS1_OAEP object
decrypted_message = decrypt.decrypt(cipher_text)
print(decrypted_message)
Comment

PREVIOUS NEXT
Code Example
Python :: find sum of factors of a number python 
Python :: python draw circle matplotlib 
Python :: tuple plot python 
Python :: pandas copy data from a column to another 
Python :: print type error python 
Python :: how to count how many cameras you have with python 
Python :: python print 2 decimal places 
Python :: python count occurrences of an item in a list 
Python :: google translator api pyhton 
Python :: how to use function in python 
Python :: mid point formula 
Python :: create empty numpy array without shape 
Python :: json decode py 
Python :: python cocktail sort 
Python :: if main python 
Python :: python property 
Python :: how to run python file 
Python :: create qr code in python 
Python :: download from colab to local drive 
Python :: python to mac executable 
Python :: python string remove accent 
Python :: square root in python 
Python :: pyqt button clicked connect 
Python :: python plot two lines with different y axis 
Python :: in python how to use exp 
Python :: how to plot labeled data with different colors 
Python :: join() python 
Python :: add new row to numpy array 
Python :: zip python 
Python :: dataframe python unique values rows 
ADD CONTENT
Topic
Content
Source link
Name
3+2 =