Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement OpenSSL functionality in Python?

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?

like image 515
user966151 Avatar asked Oct 06 '11 01:10

user966151


People also ask

Does Python install OpenSSL?

Currently Python versions 3.6 to 3.9 are compatible with OpenSSL 1.0. 2, 1.1. 0, and 1.1. 1.

Is ssl built in Python?

Most of the code for the ssl module is written in C, rather than in Python.


2 Answers

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:

  • M2Crypto (seems to be Python 2 only)

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

like image 141
jfs Avatar answered Sep 22 '22 22:09

jfs


Probably the easiest way to get exactly the same behaviour would be using pyOpenSSL - it's a thin Python wrapper for OpenSSL itself.

like image 27
emboss Avatar answered Sep 21 '22 22:09

emboss