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  bunch of ASN.1/PEM plain/encrypted private keys in PKCS#8
9# format on stdin, parse each into plain text, 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 rfc5208
18
19if len(sys.argv) != 1:
20    print("""Usage:
21$ cat pkcs8key.pem | %s""" % sys.argv[0])
22    sys.exit(-1)
23
24cnt = 0
25
26while True:
27    idx, substrate = pem.readPemBlocksFromFile(
28        sys.stdin,
29        ('-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'),
30        ('-----BEGIN ENCRYPTED PRIVATE KEY-----', '-----END ENCRYPTED PRIVATE KEY-----')
31    )
32    if not substrate:
33        break
34
35    if idx == 0:
36        asn1Spec = rfc5208.PrivateKeyInfo()
37    elif idx == 1:
38        asn1Spec = rfc5208.EncryptedPrivateKeyInfo()
39    else:
40        break
41
42    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)
43
44    if rest:
45        substrate = substrate[:-len(rest)]
46
47    print(key.prettyPrint())
48
49    assert encoder.encode(key) == substrate, 'pkcs8 recode fails'
50
51    cnt += 1
52
53print('*** %s PKCS#8 key(s) de/serialized' % cnt)
54