python - 使用纯 python 读取 PKCS#7 签名数据的证书

标签 python x509 pkcs#7

已经有很多问题了,但问题是,没有一个有足够的答案如何去做,尤其是在使用 python3 时。

基本上,我想阅读 JAR/APK 证书,例如:Link to ASN1 Decoder, with Android Test Signing Key

现在有几种选择:

  • pyasn1:似乎可以工作,但只能解析原始 ASN.1 格式
  • M2Crypto:仅适用于 py2
  • Chilkat:不是免费的,尽管 CkCert 似乎是免费的
  • 加密:无法加载证书,因为 X509 证书在 PKCS#7 容器中

我找到了一种使用 pyasn1 从 pkcs#7 消息中解压证书的方法,然后使用密码学来读取它:

from pyasn1.codec.der.decoder import decode
from pyasn1.codec.der.encoder import encode
from cryptography import x509
from cryptography.hazmat.backends import default_backend

cdata = open("CERT.RSA", "rb").read()
cert, rest = decode(cdata)
# The cert should be located there
realcert = encode(cert[1][3])
realcert = realcert[2 + (realcert[1] & 0x7F) if realcert[1] & 0x80 > 1 else 2:]  # remove the first DER identifier from the front
x509.load_der_x509_certificate(realcert, default_backend())

给出

<Certificate(subject=<Name([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.6, name=countryName)>, value='US')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.8, name=stateOrProvinceName)>, value='California')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.7, name=localityName)>, value='Mountain View')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.10, name=organizationName)>, value='Android')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.11, name=organizationalUnitName)>, value='Android')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value='Android')>, <NameAttribute(oid=<ObjectIdentifier(oid=1.2.840.113549.1.9.1, name=emailAddress)>, value='android@android.com')>])>, ...)>

有没有其他办法让它干净整洁?

最佳答案

现在有库可以在纯 python 中执行此操作。一个是 asn1crypto:https://github.com/wbond/asn1crypto#readme 这也是在 androguard 中实现的,包括如何使用它的示例:https://androguard.readthedocs.io/en/latest/intro/certificates.html

关于python - 使用纯 python 读取 PKCS#7 签名数据的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42300197/

相关文章:

command-line - 如何使用 OpenSSL 为客户端证书创建指定 CA 私钥密码

php - 如何使用openssl提取和验证PDF签名(PKCS7)?

openssl - 如何读取X509 V3证书的 key ?

certificate - 使用KeyTool命令将PKCS7(链式证书)导入JKS

c - PKCS#7 签名验证

python - Matplotlib Pandas : display columns name inside a stacked barchart

python - 如何连接可能为空的字符串?

python - python中的字典和列表

python - 如何使用 Connexion + Tornado 更改所有错误的错误格式

c - Windows 2008R2 CA 和 OpenSSL CSR : Error parsing CSR ASN1 bad value met