Search code examples
androidpythondigital-certificatem2crypto

Use m2crypto to print certificate in apk


I would like to show android APK certificate information like the openssl command does. like

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

At first I used PyCrypto, but I found it does not include X509 format. After trying M2Crypto, it will output an error like

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

What is the correct way to show the base64-encoded certificate?


Solution

  • Inspired by pkcs7dump.py I use pyasn1 and pyasn1_modules to show the base64-encoded certificate by extracting the file in PKCS#7(RFC2315) format.

    Following is a simple script

    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')