PC & IT SUPPORT MADE EASY FORUM
Would you like to react to this message? Create an account in a few clicks or log in to continue.

RSA Python Encryption & Decryption Example That Works

Go down

RSA Python Encryption & Decryption Example That Works Empty RSA Python Encryption & Decryption Example That Works

Post by jamied_uk 3rd December 2022, 20:58

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
jamied_uk
jamied_uk
Admin

Posts : 2952
Join date : 2010-05-09
Age : 41
Location : UK

https://jnet.sytes.net

Back to top Go down

RSA Python Encryption & Decryption Example That Works Empty Re: RSA Python Encryption & Decryption Example That Works

Post by jamied_uk 3rd December 2022, 22:28

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)
jamied_uk
jamied_uk
Admin

Posts : 2952
Join date : 2010-05-09
Age : 41
Location : UK

https://jnet.sytes.net

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum