简体   繁体   中英

How do I read(open) an ASN.1 file in python

I want to get a certificates serial number using python:

der = open('/Users/me/MyApp/Payload/codesign0').read()```
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der
cert.get_serial_number()

Unfortunately it fails in the first line:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 1: invalid start byte

How do I read an ASN.1 file format (DER) in Python?

You are opening the file as a text file, which means read tries to decode the data using UTF-8 in order to return a str object.

Instead, open it as a binary file, so that read simply returns a bytes object without trying to decode the data at all.

 der = open('...', 'rb').read()

You should try this Python-ASN1 encoder and decoder . Works for Python 2.6+ and 3.3+. Short example on page:

https://pypi.org/project/asn1/

Make sure to install pip install future before pip install asn1

PyOpenSSL is being deprecated, so might want to consider using the cryptography module instead

import cryptography
der = open('...', 'rb').read()
cert = cryptography.x509.load_der_x509_certificate(der)
cert.serial_number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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