Minchey
Minchey

Reputation: 21

Need help converting ASN1(x509)

Stuck on trying to convert my outcome from "20190211004950Z"(ASN1) to "2019-02-11"(Standard date) Before anyone asks, it's just a simple SSL expiry check and the date creation/expiration dates keep being output like I posted earlier.

My code looks like this

          **

    **import OpenSSL
import socket
import ssl
from pprint import pprint
from urllib.error import URLError, HTTPError
from urllib.request import Request, urlopen
import datetime


def get_certificate(port=443, timeout=10):
    """

    :param timeout:
    :type port: object
    """
    context = ssl.create_default_context()
    # test=(host,port)
    host = input("enter a URL")
    conn = socket.create_connection(address=(host, port))

    sock = context.wrap_socket(conn, server_hostname=host)

    sock.settimeout(timeout)
    try:
        der_cert = sock.getpeercert(True)
    finally:
        sock.close()
    return ssl.DER_cert_to_PEM_cert(der_cert)


certificate = get_certificate()
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate)


result = {
    'subject': dict(x509.get_subject().get_components()),
    'issuer': dict(x509.get_issuer().get_components()),
    'serialNumber': x509.get_serial_number(),
    'version': x509.get_version(),
    'notBefore': str(x509.get_notBefore()),
    'notAfter': str(x509.get_notAfter())
}

extensions = (x509.get_extension(i) for i in range(x509.get_extension_count()))
extension = (e.get_short_name() for e in extensions)
result.update(name=extension)
pprint(result)**

**

Any help would be appreciated

Upvotes: 2

Views: 1949

Answers (4)

sam
sam

Reputation: 132

The outcome from 'notAfter': str(x509.get_notAfter()) is not an asn1 string. It would be "b'20190211004950Z'" in your case for example. By using decode() instead of str() method would solve the problem. Other than that @maxadamo solution would work perfect for me. Thank you.

'notAfter': x509.get_notAfter().decode()

Upvotes: 0

maxadamo
maxadamo

Reputation: 534

You want to extract YYYY-MM-DD from 20190211004950Z.

It's one line only:

import datetime

asn1_time = '20190211004950Z'

datetime.datetime.strptime(asn1_time, '%Y%m%d%H%M%S%fZ').strftime("%Y-%m-%d")

Upvotes: 2

AMC
AMC

Reputation: 2702

Is your string guaranteed to always follow the format: 4 digits for the year + 2 digits for the month + digits the day? What about all those characters that comes after, are they relevant? What are they determined by?

For now, here is a solution which assumes that the date follows the same format, and that the rest of the string should be ignored:

import datetime


parse_format = ‘%Y%m%d’
out_format = ‘%Y-%m-%d’

str_1 = ‘20190211004950Z’

parse_date_res = datetime.datetime.strptime(str_1[:8], parse_format)

date_str_out = parse_date_res.strftime(out_format)

This code parses the string into a date object first, since I wasn’t completely sure if you just wanted a string as output. In any case, if there is nothing stopping you from using a date object then you probably should!

Upvotes: 0

user2822515
user2822515

Reputation: 95

result = '20190211004950Z'

formatted_result = '{}-{}-{}'.format(result[:4],result[4:6],result[6:8])

Upvotes: 0

Related Questions