How to implement OpenSSL functionality in Python?

user966151 picture user966151 · Oct 6, 2011 · Viewed 12.1k times · Source

I would like to encrypt a secret text by public-key and decrypt it by private-key in Python. I can achieve that with the openssl command:

echo "secrettext/2011/09/14 22:57:23" | openssl rsautl -encrypt -pubin -inkey public.pem | base64  data.cry
base64 -D data.cry | openssl rsautl -decrypt -inkey private.pem

How would one implement that in Python?

Answer

jfs picture jfs · Oct 6, 2011

Encrypt

#!/usr/bin/env python
import fileinput
from M2Crypto import RSA

rsa = RSA.load_pub_key("public.pem")
ctxt = rsa.public_encrypt(fileinput.input().read(), RSA.pkcs1_oaep_padding)
print ctxt.encode('base64')

Decrypt

#!/usr/bin/env python
import fileinput
from M2Crypto import RSA

priv = RSA.load_key("private.pem")
ctxt = fileinput.input().read().decode('base64')
print priv.private_decrypt(ctxt, RSA.pkcs1_oaep_padding)

Dependencies:

See also How to encrypt a string using the key and What is the best way to encode string by public-key in python.