Monday, January 18, 2016

Encrypt/decrypt a string with RSA public/private PEM files using Python

This post shows how to:

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

Public Key and Private Key Generation


1. Generate a 1024-bit private key:

openssl genrsa -out private_key.pem 1024

2. Obtain a public key from the private key:

openssl rsa -in private_key.pem -pubout -out public_key.pem

Encrypt and decrypt a string using Python

1. Install Python-Crypto.

sudo apt-get install python-crypto




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


from Crypto.PublicKey import RSA

public_key_string = open("public_key.pem","r").read()
public_key = RSA.importKey(public_key_string)

private_key_string = open("private_key.pem","r").read()
private_key = RSA.importKey(private_key_string)

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.py


References:
Encrypt/decrypt a string with RSA public/private keys in PHP
Encrypt/decrypt a string with code-generated RSA public/private keys in Python
Sending an RSA encrypted message from client to Python socket server

iOS:
Encrypt/decrypt a string with RSA public/private keys in Swift
Encrypt/decrypt a string with public/private keys imported from PEM files (Swift)

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

No comments:

Post a Comment