Python:使用pyOpenSSL.crypto读取pkcs12证书

nem*_*ign 15 python openssl cryptography pyopenssl digital-certificate

我有西班牙当局(FNMT)颁发的有效证书,我想玩它以了解更多相关信息.该文件的扩展名为.p12

我想阅读其中的信息(名字和姓氏)并检查证书是否有效.用pyOpenSSL可以做到吗?我想我必须在OpenSSL中使用加密模块.任何帮助或有用的链接?试着在这里阅读:http://packages.python.org/pyOpenSSL/openssl-crypto.html但信息不多:-(

小智 37

这是非常直接的使用.这不是测试,但应该工作:

# load OpenSSL.crypto
from OpenSSL import crypto

# open it, using password. Supply/read your own from stdin.
p12 = crypto.load_pkcs12(open("/path/to/cert.p12", 'rb').read(), passwd)

# get various properties of said file.
# note these are PyOpenSSL objects, not strings although you
# can convert them to PEM-encoded strings.
p12.get_certificate()     # (signed) certificate object
p12.get_privatekey()      # private key.
p12.get_ca_certificates() # ca chain.
Run Code Online (Sandbox Code Playgroud)

有关更多示例,请查看pyopenssl单元测试代码.您可能希望使用该库的各种方式

另请参见这里或没有广告在这里.

  • python3解决方案怎么样?我遇到了load_pkcs12的问题,因为现在没有文件命令,我用open()尝试的任何操作都给了我很多错误.:(当尝试:`p12 = load_pkcs12(open('foo.p12','rb').read(),passwd)`我收到:`OpenSSL.crypto.Error:[('asn1 encoding routine', 'ASN1_get_object','标题太长')]` (2认同)

tar*_*dyp 16

由于 pyOpenSSL.crypto.load_pkcs12 现已弃用,因此这里是使用加密技术的等效解决方案,并在请求会话中加载作为奖励。

from cryptography.hazmat.primitives import serialization
from requests import Session

with open("./cert.p12", "rb") as f:
    (
        private_key,
        certificate,
        additional_certificates,
    ) = serialization.pkcs12.load_key_and_certificates(
        f.read(), CLIENT_CERT_KEY.encode()
    )
# key will be available in user readable temporary file for the time of the
# program run (until key and cert get gc'ed)
key = tempfile.NamedTemporaryFile()
cert = tempfile.NamedTemporaryFile()
key.write(
    private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
)
key.flush()
cert.write(
    certificate.public_bytes(serialization.Encoding.PEM),
)
cert.flush()
session = Session()
session.cert = (cert.name, key.name)
Run Code Online (Sandbox Code Playgroud)

  • 这有效,我只需添加该方法的手动导入(“import cryptography.hazmat.primitives.serialization.pkcs12”),否则我会收到属性错误(“AttributeError:模块'cryptography.hazmat.primitives.serialization”有没有属性“pkcs12”`) (4认同)