1#!/usr/bin/env python
2#
3# This file is part of pyasn1-modules software.
4#
5# Copyright (c) 2005-2019, Ilya Etingof <[email protected]>
6# License: http://snmplabs.com/pyasn1/license.html
7#
8# Read ASN.1/PEM PKCS#7 on stdin, parse it 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 rfc2315
18
19if len(sys.argv) != 1:
20    print("""Usage:
21$ cat pkcs7Certificate.pem | %s""" % sys.argv[0])
22    sys.exit(-1)
23
24idx, substrate = pem.readPemBlocksFromFile(
25    sys.stdin, ('-----BEGIN PKCS7-----', '-----END PKCS7-----')
26)
27
28assert substrate, 'bad PKCS7 data on input'
29
30contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
31
32if rest:
33    substrate = substrate[:-len(rest)]
34
35print(contentInfo.prettyPrint())
36
37assert encoder.encode(contentInfo) == substrate, 're-encode fails'
38
39contentType = contentInfo.getComponentByName('contentType')
40
41contentInfoMap = {
42    (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(),
43    (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(),
44    (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(),
45    (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(),
46    (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(),
47    (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData()
48}
49
50content, _ = decoder.decode(
51    contentInfo.getComponentByName('content'),
52    asn1Spec=contentInfoMap[contentType]
53)
54
55print(content.prettyPrint())
56