简体   繁体   English

如何在python中验证服务器的SSL证书?

[英]How to validate server's ssl certificate in python?

I have configured my server to serve only https creating a self-signed certificate. 我已将服务器配置为仅服务于创建自签名证书的https。 I have a client that I has to validate the server's certificate and after that will download a file from the server. 我有一个必须验证服务器证书的客户端,此后,它将从服务器下载文件。

How do I implement the validation in client? 如何在客户端中执行验证? Is there any code example? 有没有代码示例?

My question is similar with this one: How can the SSL client validate the server's certificate? 我的问题与此相似: SSL客户端如何验证服务器的证书? but although the fine explanation, I didn't find any help. 但是尽管有很好的解释,但我没有找到任何帮助。

So far, in my code I create a directory and then I download the file with urllib2: 到目前为止,在我的代码中,我创建了一个目录,然后使用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)

Rather than configuring your server to present a self-signed certificate, you should use a self-signed certificate as a certificate authority to sign the server certificate. 与其将服务器配置为提供自签名证书,不如将自签名证书用作证书颁发机构来对服务器证书进行签名。 (How to do this is beyond the scope of your question, but I'm sure you can find help on Stack Overflow or elsewhere.) (如何执行此操作超出了您的问题范围,但是我敢肯定您可以在Stack Overflow或其他地方找到帮助。)

Now you must configure your client to trust your certificate authority. 现在,您必须配置客户端以信任您的证书颁发机构。 In python (2.7.9 or later), you can do this using the ssl module: 在python(2.7.9或更高版本)中,您可以使用ssl模块执行此操作:

import ssl

...  # create socket

ctx = ssl.create_default_context(cafile=path_to_ca_certificate)
sslsock = ctx.wrap_socket(sock)

You can then transmit and read data on the secure socket. 然后,您可以在安全套接字上传输和读取数据。 See the ssl module documentation for more explanation. 有关更多说明,请参见ssl模块文档

The urllib2 API is simpler: urllib2 API更简单:

import urllib2

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

If you wish to use Requests, according to the documentation you can supply a path to the CA certificate as the argument to the verify parameter: 如果您希望使用请求,则根据文档,您可以提供CA证书的路径作为verify参数的参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM