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