2016-12-15 1 views
0

서버 인증서를 DER 파일로 다운로드해야합니다. 파이썬을 사용하고 있습니다. 이 스크립트를 사용하여 서버에 연결할 수 있지만 다음 단계에서 구문 분석 할 수 있도록 인증서를 로컬 하드 디스크에 다운로드해야합니다.Python을 사용하여 x509 인증서를 다운로드하는 방법

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) 

답변

0

당신은 중간 변환의 부부와 함께 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) 
+0

가 열려 ('/ tmp를/google.der'에 대해 조금 명확히 할 수 WB : 당신이 필요로하는 당신이 일을해야 할 유일한 것은 당신이 할 DER로 get_server_certificate에 의해 반환되는 PEM을 변환하는 것입니다 ') f : f.write (der)'? 오류가 발생합니다 : FileNotFoundError : [Errno 2] 해당 파일이나 디렉토리가 없습니다 : '/tmp/google.der' ', 비록 프로젝트 폴더 안에 tmp 폴더를 만들었습니다. 나는 또한'open ('../ tmp/google.der', 'wb')'를 시도했지만 문제를 해결하지 못했다. – user2192774

+0

@ user2192774 시스템에'/ tmp' 디렉토리가 없으므로 아마도이 오류가 발생합니다. 이 경우 대신 'open ('google.der ','wb) '을 실행하십시오. –

1

명시 적으로 이미 당신을 위해 이것을 할 것 get_server_certificate 이후 서버에 연결할 필요가 없습니다. '

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)) 
관련 문제