use*_*774 5 python ssl ssl-certificate x509 python-3.x
我需要将服务器证书下载为 DER 文件。我正在使用Python。我可以使用此脚本连接到服务器,但我需要将证书本地下载到我的硬盘中,以便我可以在下一阶段解析它。
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)
Run Code Online (Sandbox Code Playgroud)
无需显式连接到服务器,因为get_server_certificate它已经为您完成了此操作。您唯一需要的就是将返回的 PEM 转换get_server_certificate为您想要的 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))
Run Code Online (Sandbox Code Playgroud)
您可以通过几个中间转换来保存 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8739 次 |
| 最近记录: |