RSA PKI based encryption and decryption in python

Generate RSA key pair in pem format

openssl genrsa -out private.pem 2048

Remember above pem file contains private and public key. Keep it secure with yourself.

Extract public key out of pem file

ssh-keygen -f private.pem -m 'PEM' -e > public.pem

Now you have private key embedded in private.pem file along with public key. And a copy of public key is available in public.pem file. You can share public.pem file with the people from whom you want to receive encrypted messages.

Here is a the python code to read private and public keys. Remember messages are always encrypted using public key (by anyone) and decrypted by owner using private key.

Code demonstrates use of public key to encrypt message and private key to decrypt message.

#!/usr/bin/python3
import rsa

with open('private.pem') as privatefile:
        p = privatefile.read()
        privkey = rsa.PrivateKey.load_pkcs1(p)

with open('public.pem') as publickfile:
        p = publickfile.read()
        pubkey = rsa.PublicKey.load_pkcs1(p)

message = "Good morning !"
enMessage = rsa.encrypt(message.encode(),pubkey)
 
print("original string: ", message)
print("encrypted string: ", enMessage)
 
deMessage = rsa.decrypt(enMessage, privkey).decode()
 
print("decrypted string: ", deMessage)

Try it out

manish@TreeHouse:~/pyPKI$ ./pyPKI.py 

original string:  Good morning !

encrypted string:  b'\x89\xe1\xb6\xffdWL\x8d.\xf8[\x96\x10\x9a\x99\x06\x95J\xb5Z|t\xf2Dz\xae\xe9\xf8>U \x87\xd4\x8a?\xf0H\xd9\x19\xb772\xd3\x1c\xa2\xd6\xba\xab$\xeb\x1d\xfc\x067\xaf9\xf41\xd4SP0z\x10\x93K8.p\x9b\xc0\x8e\xcd\x16v`\xf1\x8d\xe45\xa2\x90?\x15\xe9Z:h\xc7.\x88\xfe\xafn\xde_\xcds&\xd8\xf7\x1a\x055\xd9K\n-\xb0v\xc3c\x7f\xf2N\xd2\xb1\x96\x14l\xb6\x7fo\xd33\xbc*D\xc2\x9d.\x07\xcc?\x16R\x9d!\x16\xc6\xf7<\x9e\xa3Qa\x01;\xe4\x11\xff\x1d!\xbe\xa4if"\xda\xc3\x81\xd1zp\xe2\x1e\xe9\xbc\x06\x1f*\x90\xfao\xae\xe3\x9a\x87\xd0{yxrO\xf5\xcc\xd9k\x96\n\x00k\xfc\xdd1f\x06\x91\xa8\xcb\xf2l\x97\xe3h\x87\xcdU\x1b\x9b\x9c\xe9\xd8\xd12K|!\xef\xc5^@\xf3\x9d\xb8\x01\x91k~"Z\xe6\xca\x03\xae\xd8\x03\x84\x12\xc2\xdc;\x1d\xbf\xf9@{q\n\xffZ\xba\x8e\xae\xfd\xed'

decrypted string:  Good morning !