代码之家  ›  专栏  ›  技术社区  ›  Ned Batchelder

将客户端证书与URLLIB2一起使用

  •  16
  • Ned Batchelder  · 技术社区  · 15 年前

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

    1. 如何将自己的客户端证书与URLLIB2一起使用?

    2. 我需要在代码中做什么来确保远程证书是正确的?

    4 回复  |  直到 7 年前
        1
  •  11
  •   Hank Gay    15 年前

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

        2
  •  32
  •   tghw megawac    14 年前

    因为Alex的答案是一个链接,而且页面上的代码格式不好,所以我将在这里为子孙后代介绍:

    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()
    
        3
  •  3
  •   Leynos    8 年前

    根据安托万·皮特鲁对汉克·盖伊答案中相关问题的回答,这可以通过使用包含的内容在一定程度上简化(截至2011年)。 ssl 图书馆:

    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())
    

    (python 3代码,但是 SSL 库也可以在python 2中使用)。

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