【问题标题】:How to validate server's ssl certificate in python?如何在 python 中验证服务器的 ssl 证书?
【发布时间】:2015-05-11 06:49:37
【问题描述】:

我已将我的服务器配置为仅提供 https 以创建自签名证书。我有一个客户端,我必须验证服务器的证书,然后从服务器下载文件。

如何在客户端实现验证?有代码示例吗?

我的问题与此类似:How can the SSL client validate the server's certificate? 但是虽然很好的解释,但我没有找到任何帮助。

到目前为止,我在我的代码中创建了一个目录,然后使用 urllib2 下载文件:

[...] #imports

def dir_creation(path):
try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise


def file_download(url):
ver_file = urllib2.urlopen(url)
data = ver_file.read()
with open(local_filename, "wb") as code:
    code.write(data)

dir_creation(path)
file_download(url)

【问题讨论】:

    标签: python ssl certificate verify


    【解决方案1】:

    您应该使用自签名证书作为证书颁发机构来签署服务器证书,而不是将您的服务器配置为提供自签名证书。 (如何做到这一点超出了您的问题范围,但我相信您可以在 Stack Overflow 或其他地方找到帮助。)

    现在您必须将客户端配置为信任您的证书颁发机构。在 python(2.7.9 或更高版本)中,您可以使用 ssl 模块执行此操作:

    import ssl
    
    ...  # create socket
    
    ctx = ssl.create_default_context(cafile=path_to_ca_certificate)
    sslsock = ctx.wrap_socket(sock)
    

    然后您可以在安全套接字上传输和读取数据。更多解释请参见ssl module documentation

    urllib2 API 更简单:

    import urllib2
    
    resp = urllib2.urlopen(url, cafile=path_to_ca_certificate)
    resp_body = resp.read()
    

    如果您想使用请求,根据文档,您可以将supply a path to the CA certificate 作为verify 参数的参数:

    resp = requests.get(url, verify=path_to_ca_certificate)
    

    【讨论】:

    • 我已经用我的代码更新了这个问题,我已经使用了 urllib2 方法。所以你说它可以验证证书?我无法获取此参数:cafile=path_to_ca_certificate。是客户的证书吗?能详细点吗?
    • 它登陆了 Python 2.7.9,它向后移植了对 ssl 模块的改进。如果您使用的是 Python 2,则应升级到 2.7.9。
    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 2016-05-24
    • 2012-11-14
    • 2015-06-24
    • 1970-01-01
    • 2014-08-02
    • 2013-02-08
    • 1970-01-01
    相关资源
    最近更新 更多