简体   繁体   English

如何使用python下载x509证书

[英]How to download x509 certificate using python

I need to download servers certificates as DER file. 我需要将服务器证书下载为DER文件。 I am using python. 我正在使用python。 I could connect to the server using this script but I need to download the certificate locally in my hard disk so I can parse it in the next stage. 我可以使用此脚本连接到服务器,但是我需要将证书本地下载到硬盘上,以便在下一步进行解析。

import socket, ssl
import OpenSSL

hostname='www.google.com'
port=443

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname=hostname)
ssl_sock.connect((hostname, port))
ssl_sock.close()
print("ssl connection Done")

cert = ssl.get_server_certificate((hostname, port))

# OpenSSL
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)

There is no need to explicitly connect to the server since get_server_certificate will already do this for you. 无需显式连接到服务器,因为get_server_certificate已为您完成此操作。 The only thing you need thing you need is to convert the PEM returned by get_server_certificate into the DER you want to have: 您唯一需要做的就是将get_server_certificate返回的PEM转换为您想要的DER:

import ssl
hostname='www.google.com'
port=443

f = open('cert.der','wb')
cert = ssl.get_server_certificate((hostname, port))
f.write(ssl.PEM_cert_to_DER_cert(cert))

You can save the DER file with a couple of intermediate transformations: 您可以通过一些中间转换来保存DER文件:

cert = ssl.get_server_certificate((hostname, port))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
der = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)
with open('/tmp/google.der', 'wb') as f: f.write(der)

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

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