How do I read(open) an ASN.1 file in python
Question:
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?
Answers:
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
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()
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
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 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
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()
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