Wednesday, February 24, 2016

Using OpenSSL to decrypt an encrypted message exported by Python

This tutorial involves three parts:

(1) OpenSSL: Generate a private and public key pair using. 
(2) Python: Use the public key to export an encrypted message.
(3) OpenSSL: Decrypt the message using the private key.

(1) OpenSSL

Generate an RSA private and public key pair in PEM format.

1. Generate a 1024-bit private key:

sudo openssl genrsa -out private_key.pem 1024

2. Obtain a public key from the private key:

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

(2) Python

1. Edit a Python file called encrypt.py as:


from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

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

# Generate a cypher using the PKCS1 v1.5 standard.
# See: GitHub: EncryptionExample/python/encrypt.py
cipher = PKCS1_v1_5.new(public_key)

message = "Secret message in Python file"

encrypted = cipher.encrypt(message)

f = open("encrypted.txt","w")
f.write(encrypted)
f.close()

print "OK"

2. Produce the  file with this command:

sudo python encrypt.py

(3) OpenSSL



Decrypt encrypted.txt with private_key.pem using this command:


openssl rsautl -in encrypted.txt -decrypt -inkey private_key.pem

Note


PKCS#1 v1.5 padding is required in encrypt.py. Without it, this error may happen with the OpenSSL decryption command:


RSA operation error

rsa routines:RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:rsa_eay.c:523:

References:

Encrypt/decrypt a string with code-generated RSA public/private keys in Python
Encrypt/decrypt a string with RSA public/private PEM files using Python
OpenSSL RSA commands to encrypt/decrypt a message in terminal

No comments:

Post a Comment