我需要在我的服务器和远程网络服务之间创建一个安全通道。 我将使用带有客户端证书的HTTPS。 我还需要验证远程服务呈现的证书。
如何使用urllib2使用自己的客户端证书?
我需要在我的代码中做什么来确保远程证书是正确的?
我需要在我的服务器和远程网络服务之间创建一个安全通道。 我将使用带有客户端证书的HTTPS。 我还需要验证远程服务呈现的证书。
如何使用urllib2使用自己的客户端证书?
我需要在我的代码中做什么来确保远程证书是正确的?
由于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()
根据 Antoine Pitrou 对 Hank Gay 的回答中提到的问题,(截至 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
函数还接受一个可选的密码参数,允许对私钥进行加密。