ASCII-armored and PEM are very similar. You just need to change the BEGIN / END markers, split the PGP headers and checksums. I have done this before in PHP. I just ported it to Python for you,
import re
import StringIO
def pgp_pubkey_to_pem(pgp_key):
pgp_key = re.compile('(\n|\r\n|\r)').sub('\n', pgp_key)
buffer = StringIO.StringIO()
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-----'):
break
elif in_body and line.startswith('='):
break
elif in_body:
buffer.write(line+'\n')
buffer.write('-----END RSA PUBLIC KEY-----\n')
return buffer.getvalue()
source
share