使用urllib2的客户端证书

Ned*_*der 19 python ssl certificate urllib2 mutual-authentication

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

  1. 如何在urllib2中使用自己的客户端证书?

  2. 我需要在代码中做些什么才能确保远程证书正确无误?

tgh*_*ghw 34

因为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()
Run Code Online (Sandbox Code Playgroud)


Han*_*Gay 11

这是官方Python bugtracker中的一个看起来相关的错误,并且有一个建议的补丁.


Ley*_*nos 5

Per Antoine Pitrou对Hank Gay的答案中相关问题的回应,可以通过使用随附的ssl库在某种程度上简化(自2011年起):

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())
Run Code Online (Sandbox Code Playgroud)

(Python 3代码,但该ssl库在Python 2中也可用)。

load_cert_chain函数还接受可选的password参数,从而可以对私钥进行加密。