user2192774
user2192774

Reputation: 3907

How to extract x509 in python

I have the following script. It connects to a TLS server and extracts some X509 data such as validity dates and public-key. I have the following script:

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)
pk = x509.get_pubkey()
print(x509.get_notAfter())
print(x509.get_notBefore())
print(pk)

The problem is that the validity dates and the public-key are returned in unreadable format. How to solve this issue? i.e get the validity in date format and the public-key in hex format?

Also, how can I save the certificate file in my local disk for reference?

EDIT: This is the output I am getting:

b'20170223141600Z' 
b'20161201141600Z' 
<OpenSSL.crypto.PKey object at 0x0000019EBFDF73C8>

Upvotes: 8

Views: 10159

Answers (2)

hpr
hpr

Reputation: 164

If your goal is to get the certificate, why are you using the get_pubkey method ?

Public keys and certificates aren't the same.

To get the certificate :

buffer = dump_certificate(OpenSSL.crypto.FILETYPE_PEM, x509)
print(buffer.decode())

That will give you the base64 content of the certificate.

You will need to manually add the header

-----BEGIN CERTIFICATE-----

and the footer

-----END CERTIFICATE-----

Upvotes: 0

Alastair McCormack
Alastair McCormack

Reputation: 27714

The date returned is a YYYYMMDDHHMM formatted date. You can convert it to a datetime object with:

datetime.strptime(x509.get_notAfter().decode('ascii'), '%Y%m%d%H%M%SZ')

Upvotes: 19

Related Questions