19

サーバーとリモート Web サービスの間に安全なチャネルを作成する必要があります。クライアント証明書で HTTPS を使用します。また、リモート サービスによって提示された証明書を検証する必要もあります。

  1. urllib2 で自分のクライアント証明書を使用するにはどうすればよいですか?

  2. リモート証明書が正しいことを確認するには、コードで何をする必要がありますか?

4

4 に答える 4

37

アレックスの答えはリンクであり、そのページのコードは適切にフォーマットされていないため、後世のためにこれをここに配置します。

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()
于 2010-12-16T19:05:28.830 に答える
12

これは、関連性があり、提案されたパッチがある公式の Python バグトラッカーのバグです。

于 2009-12-09T16:34:40.253 に答える
7

Hank Gay's answer にリンクされている問題に対する Antoine Pitrou の回答によると、これは含まれている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())

(Python 3 コードですが、sslライブラリは Python 2 でも利用できます)。

このload_cert_chain関数は、オプションのパスワード パラメータも受け入れ、秘密鍵を暗号化できるようにします。

于 2016-11-25T16:39:03.883 に答える