PKCS#12 support in pyOpenSSL is deprecated
Asked Answered
Z

1

6

I would like to get the expirydate from the cert_name.pfx like in: Get .pfx Cert File Expiration with pyOpenSSL

from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.backends import default_backend

pkcs12 = crypto.load_pkcs12(open('cert.pfx', "rb").read(), '1234')
pem_data = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate())
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
print(cert.not_valid_after)

I got the following errors:

  1. DeprecationWarning: PKCS#12 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.
  2. DeprecationWarning: str for passphrase is no longer accepted, use bytes. Coming from this line:

The second error disappeared after ....read(), b'1234') I added the 'b'

If I can use this anymore: crypto.load_pkcs12(open('cert.pfx', "rb").read(), '1234')

What can I use instead in reading the expiry date of a pkcs12 formatted certificate? (Using python 3.8)

Zworykin answered 7/1, 2021 at 15:49 Comment(0)
K
18

Use cryptography.hazmat.primitives.serialization.pkcs12.load_key_and_certificates.

Example:

from cryptography.hazmat.primitives.serialization import pkcs12

with open("cert.pfx", "rb") as f:
    private_key, certificate, additional_certificates = pkcs12.load_key_and_certificates(f.read(), b"1234")
print(certificate.not_valid_after)
Kesler answered 7/1, 2021 at 16:28 Comment(3)
Thanks a lot. That did the job :-)Zworykin
@Sboerhoop, please consider voting the answer up or accepting it. See: What should I do when someone answers my question?Emmaline
This works for me in Pycharm under unix, but under Windows 10 with Pycharm it doesn't. I got the following error: "Could not deserialize data" What could that be?Zworykin

© 2022 - 2024 — McMap. All rights reserved.