1#!/usr/bin/env python
2#
3# This file is part of pyasn1-modules software.
4#
5# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
6# License: http://snmplabs.com/pyasn1/license.html
7#
8# Read ASN.1/PEM X.509 certificates on stdin, parse each into plain text,
9# then build substrate from it
10#
11import sys
12
13from pyasn1.codec.der import decoder
14from pyasn1.codec.der import encoder
15
16from pyasn1_modules import pem
17from pyasn1_modules import rfc2459
18
19if len(sys.argv) != 1:
20    print("""Usage:
21$ cat CACertificate.pem | %s
22$ cat userCertificate.pem | %s""" % (sys.argv[0], sys.argv[0]))
23    sys.exit(-1)
24
25certType = rfc2459.Certificate()
26
27certCnt = 0
28
29while True:
30    idx, substrate = pem.readPemBlocksFromFile(
31        sys.stdin, ('-----BEGIN CERTIFICATE-----',
32                    '-----END CERTIFICATE-----')
33    )
34    if not substrate:
35        break
36
37    cert, rest = decoder.decode(substrate, asn1Spec=certType)
38
39    if rest:
40        substrate = substrate[:-len(rest)]
41
42    print(cert.prettyPrint())
43
44    assert encoder.encode(cert) == substrate, 'cert recode fails'
45
46    certCnt += 1
47
48print('*** %s PEM cert(s) de/serialized' % certCnt)
49