python 通过*.cer *..pfx 获取公钥私钥

实例代码如下:

from OpenSSL import crypto

cer_file_path = r"D:cloudpayDjangoconf58543195931098400.cer"
pfx_file_path = r"D:cloudpayDjangoconf58543195931098400.pfx"


class ReadKey(object):
    """用于读取密钥"""

    @staticmethod
    def get_public_key(cer_file_path):
        """
        从cer证书中提取公钥
        :param cer_file: cer证书存放的路径
        :return: 公钥
        """
        cert = crypto.load_certificate(crypto.FILETYPE_ASN1, open(cer_file_path, "rb").read())
        res = crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey()).decode("utf-8")
        return res.strip()

    @staticmethod
    def get_private_key(pfx_file_path, password="12345678"):
        """
        从pfx证书中提取私钥,如果证书已加密,需要输入密码
        :param pfx_file_path:pfx证书存放的路径
        :param password:证书密码
        :return:私钥pkey = crypto.load_pkcs12(key, password).get_privatekey()
        """
        pfx = crypto.load_pkcs12(open(pfx_file_path, 'rb').read(), bytes(password, encoding="utf8"))
        res = crypto.dump_privatekey(crypto.FILETYPE_PEM, pfx.get_privatekey())
        return res.strip()


print(ReadKey.get_public_key(cer_file_path))

print(ReadKey.get_private_key(pfx_file_path))
原文地址:https://www.cnblogs.com/wangcongxing/p/12325411.html