首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在urllib2中使用客户端证书

在urllib2中使用客户端证书
EN

Stack Overflow用户
提问于 2009-12-10 00:27:21
回答 4查看 19.6K关注 0票数 19

我需要在我的服务器和远程web服务之间创建一个安全通道。我将使用带有客户端证书的HTTPS。我还需要验证远程服务提供的证书。

  1. 如何在urllib2中使用我自己的客户端证书?
  2. 我需要在代码中执行哪些操作才能确保远程证书正确?
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-12-10 00:34:40

这是一个看起来相关的bug in the official Python bugtracker,并且有一个建议的补丁。

票数 12
EN

Stack Overflow用户

发布于 2010-12-17 03:05:29

因为alex的答案是一个链接,而该页面上的代码格式很差,所以我将把它放在这里供后人使用:

代码语言:javascript
复制
import urllib2, httplib

class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
    def __init__(self, key, cert):
        urllib2.HTTPSHandler.__init__(self)
        self.key = key
        self.cert = cert

    def https_open(self, req):
        # Rather than pass in a reference to a connection class, we pass in
        # a reference to a function which, for all intents and purposes,
        # will behave as a constructor
        return self.do_open(self.getConnection, req)

    def getConnection(self, host, timeout=300):
        return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

opener = urllib2.build_opener(HTTPSClientAuthHandler('/path/to/file.pem', '/path/to/file.pem.') )
response = opener.open("https://example.org")
print response.read()
票数 37
EN

Stack Overflow用户

发布于 2016-11-26 00:39:04

根据Antoine Pitrou对Hank Gay答案中链接的问题的回应,这可以通过使用包含的ssl库进行一定程度的简化(从2011年开始):

代码语言:javascript
复制
import ssl
import urllib.request

context = ssl.create_default_context()
context.load_cert_chain('/path/to/file.pem', '/path/to/file.key')
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
response = opener.open('https://example.org')
print(response.read())

(Python3代码,但在Python2中也提供了ssl库)。

load_cert_chain函数还接受一个可选的password参数,允许加密私钥。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1875052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档