views:

587

answers:

2

is there any python method for converting base64 encoded key to a pem format .

how to convert ASCII-armored PGP public key to a MIME encoded form.

thanks

A: 

See here for a similar question and answer, could you shell out in Python to this tool?

Preet Sangha
+2  A: 

ASCII-armored and PEM are very similar. You just need to change the BEGIN/END markers, strip the PGP headers and checksums. I've done this before in PHP. I just ported it to Python for you,

import re
import StringIO

def pgp_pubkey_to_pem(pgp_key):
    # Normalise newlines
    pgp_key = re.compile('(\n|\r\n|\r)').sub('\n', pgp_key)

    # Extract block
    buffer = StringIO.StringIO()
    # Write PEM header
    buffer.write('-----BEGIN RSA PUBLIC KEY-----\n')

    in_block = 0
    in_body = 0
    for line in pgp_key.split('\n'):
        if line.startswith('-----BEGIN PGP PUBLIC KEY BLOCK-----'):
            in_block = 1
        elif in_block and line.strip() == '':
            in_body = 1
        elif in_block and line.startswith('-----END PGP PUBLIC KEY BLOCK-----'):
            # No checksum, ignored for now
            break
        elif in_body and line.startswith('='):
            # Checksum, end of the body
            break
        elif in_body:
            buffer.write(line+'\n')

    # Write PEM footer
    buffer.write('-----END RSA PUBLIC KEY-----\n')

    return buffer.getvalue()
ZZ Coder