如何在Python中实现OpenSSL功能?

发布于 2024-12-08 10:22:11 字数 356 浏览 4 评论 0原文

我想在Python中通过公钥加密秘密文本并通过私钥解密。 我可以使用 openssl 命令来实现这一点:

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独守阴晴ぅ圆缺 2024-12-15 10:22:11

加密

#!/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')

解密

#!/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)

依赖项:

另请参阅如何使用密钥加密字符串 和 < a href="https://stackoverflow.com/questions/7563732/what-is-the-best-way-to-encode-string-by-public-key-in-python">什么是python中通过公钥对字符串进行编码的最佳方法。

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.

温柔戏命师 2024-12-15 10:22:11

获得完全相同行为的最简单方法可能是使用 pyOpenSSL - 它是 OpenSSL 本身的一个瘦 Python 包装器。

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

信愁 2024-12-15 10:22:11

m2crypto 模块向 Python 公开了 OpenSSL 的大部分功能,包括公共/私有加密、解密和签名。

大多数 Linux 发行版都提供 m2crypto 模块作为本机包。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文