1#!/usr/bin/python
2#
3# Read unencrypted PKCS#1/PKIX-compliant, PEM&DER encoded private keys on
4# stdin, print them pretty and encode back into original wire format.
5# Private keys can be generated with "openssl genrsa|gendsa" commands.
6#
7from pyasn1_modules import rfc2459, rfc2437, pem
8from pyasn1.codec.der import encoder, decoder
9import sys
10
11if len(sys.argv) != 1:
12    print("""Usage:
13$ cat rsakey.pem | %s""" % sys.argv[0])
14    sys.exit(-1)
15
16cnt = 0
17
18while 1:
19    idx, substrate = pem.readPemBlocksFromFile(sys.stdin, ('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----'), ('-----BEGIN DSA PRIVATE KEY-----', '-----END DSA PRIVATE KEY-----') )
20    if not substrate:
21        break
22
23    if idx == 0:
24        asn1Spec = rfc2437.RSAPrivateKey()
25    elif idx == 1:
26        asn1Spec = rfc2459.DSAPrivateKey()
27    else:
28        break
29
30    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)
31
32    if rest: substrate = substrate[:-len(rest)]
33
34    print(key.prettyPrint())
35
36    assert encoder.encode(key, defMode=False) == substrate or \
37           encoder.encode(key, defMode=True) == substrate, \
38           'pkcs8 recode fails'
39
40    cnt = cnt + 1
41
42print('*** %s key(s) re/serialized' % cnt)
43