使用m2crypto在apk中打印证书

Use m2crypto to print certificate in apk

我想像 openssl 命令那样显示 android APK 证书信息。喜欢

$ openssl pkcs7 -inform DER -in CERT.RSA -print_certs
subject=...
-----BEGIN CERTIFICATE-----
MIIEBzCCAu+gAwIBAgIEKkPNCjANBgkqhkiG9w0BAQsFADCBsjEPMA0GA1UEBhMG
...
5be3OOWPt+mHkeWxsei9r+S7tuWkp+WOpjEVMBMGA1UECgwM6YeR5bGx572R57uc
-----END CERTIFICATE-----

一开始我用的是PyCrypto,后来发现不包含X509格式。尝试M2Crypto后,会输出类似

的错误
In [7]: X509.load_cert('CERT.RSA', X509.FORMAT_DER)
---------------------------------------------------------------------------
X509Error                                 Traceback (most recent call last)
<ipython-input-7-821a670a1ab6> in <module>()
----> 1 X509.load_cert('CERT.RSA', X509.FORMAT_DER)

/usr/local/lib/python2.7/dist-packages/M2Crypto/X509.pyc in load_cert(file, format)
    613         cptr = m2.d2i_x509(bio._ptr())
    614         if cptr is None:
--> 615             raise X509Error(Err.get_error())
    616         return X509(cptr, _pyfree=1)
    617     else:

X509Error: 140335753901888:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337:
140335753901888:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:388:Type=X509_CINF
140335753901888:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:769:Field=cert_info, Type=X509

显示 base64 编码证书的正确方法是什么?

灵感来自 pkcs7dump.py I use pyasn1 and pyasn1_modules to show the base64-encoded certificate by extracting the file in PKCS#7(RFC2315) 格式。

下面是一个简单的脚本

from pyasn1.codec.der import decoder, encoder
from pyasn1_modules import rfc2315

contentInfo, _ = decoder.decode(open('CERT.RSA', 'rb').read(), asn1Spec=rfc2315.ContentInfo())
content = contentInfo.getComponentByName('content')
signedData, _ = decoder.decode(content, asn1Spec=rfc2315.SignedData())
certs = signedData.getComponentByName('certificates')
cert = certs.getComponentByPosition(0)
print encoder.encode(cert).encode('base64')