Python httplib.HTTPS连接和密码

发布于 2024-09-07 00:26:40 字数 331 浏览 1 评论 0原文

我将 httplib.HTTPSConnection 与私钥一起使用:

h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')

然后系统会要求我输入该私钥的密码。是否有任何选项可以不从用户输入(控制台)而是从其他源(代码、环境)输入此类密码?也许像Java中的那样:

-Djavax.net.ssl.keyStorePassword=my_secret_passwd

I use httplib.HTTPSConnection with private key:

h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')

Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (console) but from other source (code, environment)? Maybe something like in Java:

-Djavax.net.ssl.keyStorePassword=my_secret_passwd

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

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

发布评论

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

评论(1

回心转意 2024-09-14 00:26:40

私钥文件加载到 Python 的 _ssl 模块(用 C 编写的部分)中。来自 _ssl.c,第 333 行:

ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);

这是一个加载给定密钥文件的 OpenSSL 函数。如果提供了密码,它将调用密码回调函数。由于该函数默认询问用户,因此您必须使用 SSL_CTX_set_default_passwd_cb_userdata 覆盖它。不幸的是,这个函数没有包含在标准库或 M2Crypto(Python OpenSSL 包装器)中,但您可以在 pyopenssl

为了从受密码保护的密钥文件创建套接字,您必须执行以下操作:

from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_passwd_cb(lambda *unused: "yourpassword")
ctx.use_privatekey_file(keyFilename)
ctx.use_certificate_file(certFilename)
someSocket = SSL.Connection(ctx, socket.socket())

创建 HTTPS 连接有点困难,我不知道如何使用 pyopenssl 做到这一点,但 pyopenssl 中提供了一个示例源代码(test_ssl.py:242)。

The private key file is loaded in Python's _ssl module (the part that's written in C). From _ssl.c, line 333:

ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);

This is an OpenSSL function which loads the given key file. If a password is provided, it will call a password callback function. As that function defaults to asking the user, you will have to override it using SSL_CTX_set_default_passwd_cb_userdata. Unfortunately, this function is not included in the standard library or M2Crypto (Python OpenSSL wrapper), but you can find it in pyopenssl.

In order to create a socket from a password-protected key file, you would have to do something like:

from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_passwd_cb(lambda *unused: "yourpassword")
ctx.use_privatekey_file(keyFilename)
ctx.use_certificate_file(certFilename)
someSocket = SSL.Connection(ctx, socket.socket())

Creating a HTTPS connection is a bit harder and I don't know how to do it with pyopenssl, but there's an example provided in pyopenssl's source code (test_ssl.py:242).

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