[英]How do I read(open) an ASN.1 file in python
I want to get a certificates serial number using python:我想使用 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?如何读取 Python 中的 ASN.1 文件格式 (DER)?
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.您将文件作为文本文件打开,这意味着
read
尝试使用 UTF-8 解码数据以返回str
对象。
Instead, open it as a binary file, so that read
simply returns a bytes
object without trying to decode the data at all.相反,将其作为二进制文件打开,以便
read
只返回一个bytes
对象,而根本不尝试解码数据。
der = open('...', 'rb').read()
You should try this Python-ASN1 encoder and decoder
.你应该试试这个
Python-ASN1 encoder and decoder
。 Works for Python 2.6+ and 3.3+.适用于 Python 2.6+ 和 3.3+。 Short example on page:
页面上的简短示例:
https://pypi.org/project/asn1/ https://pypi.org/project/asn1/
Make sure to install pip install future
before pip install asn1
确保在 pip install asn1 之前安装
pip install future
pip install asn1
PyOpenSSL is being deprecated, so might want to consider using the cryptography module instead PyOpenSSL 已被弃用,因此可能需要考虑使用加密模块
import cryptography
der = open('...', 'rb').read()
cert = cryptography.x509.load_der_x509_certificate(der)
cert.serial_number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.