14

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?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
user966151
  • 235
  • 1
  • 5
  • 10

3 Answers3

21

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
3

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

emboss
  • 38,880
  • 7
  • 101
  • 108
1

The m2crypto module(s) expose much of OpenSSL's functionality to Python, including public/private encryption, decryption, and signing.

Most Linux distribution provide the m2crypto module as a native package.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
larsks
  • 277,717
  • 41
  • 399
  • 399
  • thanks. I know that module. But I can't write that code using m2crypto. Could you tell me information with more specific function ? – user966151 Oct 06 '11 at 03:10
  • Show me what you've tried and what sort of errors you're getting and I would be happy to help out. – larsks Oct 06 '11 at 13:42