How to implement OpenSSL functionality in Python?

不打扰是莪最后的温柔 提交于 2019-12-03 09:11:33

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/7669598/how-to-implement-openssl-functionality-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!