OpenSSL编程-Python实现公钥RSAPublicKey格式与大数字符串转换

在我们的项目开发和运维过程中,经常会遇到公钥的RSAPublicKey格式数据与BIGNUM大数字符串格式数据的转换,python的rsa模块提供这方面很便捷的转换,记录一下这两个格式之间的转换函数。

# vim: set ts=4 et sw=4 sts=4 fileencoding=utf-8 :

import rsa

def get_rsapem(n):
    """获取公钥BIGNUM对应的RSAPublicKey格式数据
    """
    try:
        bn = long(hex2bin(n), 2)
        en = long('010001', 16)
        key = rsa.key.PublicKey(bn, en)
        pem = key.save_pkcs1('PEM')
    except Exception, e:
        return None
    return pem

def get_bignum(pem):
    """获取公钥的RSAPublicKey格式数据对应的BIGNUM
    """
    try:
        pubkey = rsa.PublicKey.load_pkcs1(pem, 'PEM')
    except Exception, e:
        return None
    return dec2hex(pubkey.n)

base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)]

def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 2)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])

def dec2hex(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 16)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])

def bin2dec(string_num):
    return str(int(string_num, 2))

def bin2hex(string_num):
    return dec2hex(bin2dec(string_num))

def hex2bin(string_num):
    return dec2bin(hex2dec(string_num.upper()))

def hex2dec(string_num):
    return str(int(string_num.upper(), 16))

if __name__ == '__main__':

    print get_rsapem('145245451329625530817297100706209241927734620797553888055777700304552647658152594960271085854297377525825773733694132758305741323010877227489711681383783169618005188434721831362203821839905697959889438748628032222489913708742965733491312162302108160999578671682653114762637343084167808060391960341946603655127')

    print get_bignum('-----BEGIN RSA PUBLIC KEY-----\nMIGjAoGbAUUkVFEyliVTCBcpcQBwYgkkGSdzRiB5dVOIgFV3dwAwRVJkdlgVJZSW\nAnEIWFQpc3dSWCV3NzNpQTJ1gwV0EyMBCHcidIlxFoE4N4MWlhgAUYhDRyGDE2Ig\nOCGDmQVpeVmIlDh0higDIiJImRNwh0KWVzNJExIWIwIQgWCZlXhnFoJlMRR2Jjc0\nMIQWeAgGA5GWA0GUZgNlUScCAwEAAQ==\n-----END RSA PUBLIC KEY-----')
原创声明:除非注明,本站文章均为原创!转载请注明来自 嗨!大佟! www.qmailer.net
本文链接:http://www.qmailer.net/archives/228.html

发表评论