如何将base64 / radix64公钥转换为python中的pem格式 [英] how to convert base64 /radix64 public key to a pem format in python

查看:510
本文介绍了如何将base64 / radix64公钥转换为python中的pem格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何python方法将base64编码的密钥转换为pem格式。



如何将ASCII装甲PGP公钥转换为MIME编码格式。 p>

谢谢

解决方案

ASCII装甲和PEM非常相似。您只需要更改BEGIN / END标记,剥离PGP标头和校验和。我以前在PHP中这样做了。我只是把它移植给了你的Python,

  import re 
import StringIO

def pgp_pubkey_to_pem(pgp_key):
#规范化换行
pgp_key = re.compile('(\\\
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ pgp_key)

#提取块
buffer = StringIO.StringIO()
#写入PEM头
buffer.write('----- BEGIN RSA PUBLIC KEY ----- \\\
')

in_block = 0
in_body = 0
pgp_key.split('\\\
')中的行:
如果line.startswith('----- BEGIN PGP PUBLIC KEY BLOCK -----'):
in_block = 1
elif in_block和line.strip()=='':
in_body = 1
elif in_block和line.startswith('----- END PGP PUBLIC KEY BLOCK -----'):
#没有校验和,现在忽略
break
elif in_body和line.startswith('='):
#校验和,身体结束
b reak
elif in_body:
buffer.write(line +'\\\
')

#写PEM脚注
buffer.write('----- END RSA PUBLIC KEY ----- \\\
')

return buffer.getvalue()


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

解决方案

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()

这篇关于如何将base64 / radix64公钥转换为python中的pem格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆