Tuesday, January 19, 2016

Encrypt/decrypt a string with code-generated RSA public/private keys in Python

This post shows how to:

- generate private and public RSA keys in Python.
- encrypt and decrypt a string using Python.

1. Install Python-Crypto.

sudo apt-get install python-crypto

2. Use sudo nano rsa_generate.py command to edit a python file as below:


from Crypto.PublicKey import RSA
from Crypto import Random

#Generate private and public keys
random_generator = Random.new().read
private_key = RSA.generate(1024, random_generator)
public_key = private_key.publickey()

message = "The quick brown fox jumps over the lazy dog."

#Encrypt with public key
encrypted = public_key.encrypt(message, 32)

#Decrypt with private key
decrypted = private_key.decrypt(encrypted)


print decrypted

3. Execute the file with this command:


python rsa_generate.py

References:

Encrypt/decrypt a string with RSA public/private keys in PHP
Encrypt/decrypt a string with RSA public/private PEM files using Python
Sending an RSA encrypted message from client to Python socket server

iOS:
Encrypt/decrypt a string with code-generated RSA public/private keys in Swift

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)

No comments:

Post a Comment