RSA Python Encryption & Decryption Example That Works
RSA Python Encryption & Decryption Example That Works
- Code:
#!/usr/bin/python3
# pip install rsa
import rsa
# generate public and private keys with
# rsa.newkeys method,this method accepts
# key length as its parameter
# key length should be atleast 16
publicKey, privateKey=rsa.newkeys(1024) # 512
# this is the string that we will be encrypting
message="hello geeks"
# rsa.encrypt method is used to encrypt
# string with public key string should be
# encode to byte string before encryption
# with encode method
encMessage=rsa.encrypt(message.encode(),
publicKey)
print("original string: ", message)
print("encrypted string: ", encMessage)
# the encrypted message can be decrypted
# with ras.decrypt method and private key
# decrypt method returns encoded byte string,
# use decode method to convert it to string
# public key cannot be used for decryption
decMessage=rsa.decrypt(encMessage, privateKey).decode()
print("decrypted string: ", decMessage)
Setup rsa for python on linux
- Code:
pip install rsa
- Code:
pip3 install rsa
Re: RSA Python Encryption & Decryption Example That Works
A Python3 Example
- Code:
pip install pycryptodome
- Code:
#!/usr/bin/python3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
keyPair = RSA.generate(3072)
pubKey = keyPair.publickey()
print(f"Public key: (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
pubKeyPEM = pubKey.exportKey()
print(pubKeyPEM.decode('ascii'))
print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
privKeyPEM = keyPair.exportKey()
print(privKeyPEM.decode('ascii'))
# encryption
msg = b'A message for encryption'
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(msg)
print("Encrypted:", binascii.hexlify(encrypted))
# Decryption
decryptor = PKCS1_OAEP.new(keyPair)
decrypted = decryptor.decrypt(encrypted)
print('Decrypted:', decrypted)
Similar topics
» Python Encryption And Decryption
» Python Decryption Ceaser Cypher Shift Cypher 2021
» Securing a Python Menu With Python Encrypted Password File
» php encryption and decryption plus md5 cracking
» This command adds Python 3 as an alternative for the python command
» Python Decryption Ceaser Cypher Shift Cypher 2021
» Securing a Python Menu With Python Encrypted Password File
» php encryption and decryption plus md5 cracking
» This command adds Python 3 as an alternative for the python command
Permissions in this forum:
You cannot reply to topics in this forum
|
|