欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

pyopenssl - 下列有关openSSL的PHP代码,如果用Python实现?

程序员文章站 2022-05-31 21:51:41
...
function getCertId($cert_path) {
    $pkcs12certdata = file_get_contents ( $cert_path );

    openssl_pkcs12_read ( $pkcs12certdata, $certs, SDK_SIGN_CERT_PWD );
    $x509data = $certs ['cert'];
    openssl_x509_read ( $x509data );
    $certdata = openssl_x509_parse ( $x509data );
    $cert_id = $certdata ['serialNumber'];
    return $cert_id;
}

我写了个Python的版本,使用的是pyopenssl,如下:

'''解析pfx格式的证书ID,这里针对的是签名证书'''
def getCertIdWithPFX(cert_path):
    fp = open(cert_path, 'r')
    if not fp:
        raise Exception('open %s fail!!!' % cert_path)
    pkcs12certdata = fp.read()

    '''先解析pkcs12格式'''
    sdk_sign_cert_password = config['sdk_sign_cert_password']
    certs = OpenSSL.crypto.load_pkcs12(pkcs12certdata, sdk_sign_cert_password)

    '''然后解析x509格式'''
    x509data = certs.get_certificate()
    print x509data
    cert_data = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509data)
    print '-------------------', cert_data
    return cert_data.get_serial_number()

问题主要出在x509data,我该如何才能得到x509data中的数据呢,Python中这是个对象。

回复内容:

function getCertId($cert_path) {
    $pkcs12certdata = file_get_contents ( $cert_path );

    openssl_pkcs12_read ( $pkcs12certdata, $certs, SDK_SIGN_CERT_PWD );
    $x509data = $certs ['cert'];
    openssl_x509_read ( $x509data );
    $certdata = openssl_x509_parse ( $x509data );
    $cert_id = $certdata ['serialNumber'];
    return $cert_id;
}

我写了个Python的版本,使用的是pyopenssl,如下:

'''解析pfx格式的证书ID,这里针对的是签名证书'''
def getCertIdWithPFX(cert_path):
    fp = open(cert_path, 'r')
    if not fp:
        raise Exception('open %s fail!!!' % cert_path)
    pkcs12certdata = fp.read()

    '''先解析pkcs12格式'''
    sdk_sign_cert_password = config['sdk_sign_cert_password']
    certs = OpenSSL.crypto.load_pkcs12(pkcs12certdata, sdk_sign_cert_password)

    '''然后解析x509格式'''
    x509data = certs.get_certificate()
    print x509data
    cert_data = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509data)
    print '-------------------', cert_data
    return cert_data.get_serial_number()

问题主要出在x509data,我该如何才能得到x509data中的数据呢,Python中这是个对象。

from OpenSSL.crypto import load_pkcs12, FILETYPE_PEM, PKCS12, dump_certificate, dump_privatekey

cert_pem = dump_certificate(FILETYPE_PEM, certs .get_certificate())
key_pem = dump_privatekey(FILETYPE_PEM, certs .get_privatekey())