how to convert base64 /radix64 public key to a pem format in python

后端 未结 1 1082
闹比i
闹比i 2021-01-26 05:30

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

相关标签:
1条回答
  • 2021-01-26 06:05

    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()
    
    0 讨论(0)
提交回复
热议问题