It's fairly straight-forward to use. This isn't tested, but should work:

# 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.

For more examples, have a look through the unit test code of pyopenssl. Pretty much every way you might want to use the library is there

See also here or without adverts here.

Answer from user257111 on Stack Overflow
🌐
GitHub
github.com › ShutdownRepo › pywhisker › issues › 17
module 'OpenSSL.crypto' has no attribute 'PKCS12' · Issue #17 · ShutdownRepo/pywhisker
July 20, 2024 - module 'OpenSSL.crypto' has no attribute 'PKCS12'#17 · Copy link · h3retic · opened · on Jul 20, 2024 · Issue body actions · pywhisker.py -d example.com -u computer\$ -H 2dfcebbe9f5f4cb3bf98032887be37b6 --target User -a add [*] Searching for the target account [*] Target user found: CN=User,CN=Users,DC=example,DC=com [*] Generating certificate [*] Certificate generated [*] Generating KeyCredential [*] KeyCredential generated with DeviceID: 57ec5c73-45e5-b734-b029-8432954b1352 [*] Updating the msDS-KeyCredentialLink attribute of User [+] Updated the msDS-KeyCredentialLink attribute of the target object [!] module 'OpenSSL.crypto' has no attribute 'PKCS12' Reactions are currently unavailable ·
Author   h3retic
Top answer
1 of 3
48

It's fairly straight-forward to use. This isn't tested, but should work:

# 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.

For more examples, have a look through the unit test code of pyopenssl. Pretty much every way you might want to use the library is there

See also here or without adverts here.

2 of 3
20

As pyOpenSSL.crypto.load_pkcs12 is now deprecated, here is the equivalent solution using cryptography, with loading inside a requests Session as a bonus.

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)
Discussions

`AttributeError: module 'OpenSSL.crypto' has no attribute 'PKCS12'` under f41
You should use the APIs in ... p12 = crypto.PKCS12() ^^^^^^^^^^^^^ File "/usr/lib64/python3.13/site-packages/cryptography/utils.py", line 68, in __getattr__ obj = getattr(self._module, attr) AttributeError: module 'OpenSSL.crypto' has no attribute 'PKCS12' [root@fedora ... More on github.com
🌐 github.com
0
January 7, 2025
PyOpenSSL has removed deprecated PKCS12 breaking --shadow-credentials in ntlmrelayx.py
Configuration impacket version: 0.11.0 Python version: 3.11.8 Target OS: Kali Linux Debug Output With Command String ntlmrelayx.py -t ldaps://domain.com --shadow-credentials -smb2support --no-dump ... More on github.com
🌐 github.com
5
March 18, 2024
pyopenssl - python crypto.sign not found, though it's in the module - Stack Overflow
I'm trying to use some google api sample code, and it's not working. Admittedly, I'm green at python, but I've boiled it down to this simple test program: #!/usr/bin/python from OpenSSL import c... More on stackoverflow.com
🌐 stackoverflow.com
Exception: module 'OpenSSL.crypto' has no attribute 'PKCS12Type'
When use the script, have the warning above. Python 3.12.2 on Windows 11 23H2 Pro for Workstations. More on github.com
🌐 github.com
2
April 2, 2024
🌐
GitHub
github.com › ThePorgs › Exegol-images › issues › 367
[BUG] Impacket 'OpenSSL.crypto' has no attribute 'PKCS12' · Issue #367 · ThePorgs/Exegol-images
June 24, 2024 - There is an issue with the PyOpenSSL library used by Impacket. Indeed, we encounter the following error when trying, for example, to retrieve an ADCS certificate : AttributeError: module 'OpenSSL.crypto' has no attribute 'PKCS12'
Author   chemoms
🌐
GitHub
github.com › libreswan › libreswan › issues › 1990
`AttributeError: module 'OpenSSL.crypto' has no attribute 'PKCS12'` under f41 · Issue #1990 · libreswan/libreswan
January 7, 2025 - You should use the APIs in ... p12 = crypto.PKCS12() ^^^^^^^^^^^^^ File "/usr/lib64/python3.13/site-packages/cryptography/utils.py", line 68, in __getattr__ obj = getattr(self._module, attr) AttributeError: module 'OpenSSL.crypto' has no attribute 'PKCS12' [root@fedora ...
Published   Jan 07, 2025
🌐
PyPI
pypi.org › project › pyOpenSSL
pyOpenSSL · PyPI
Deprecated OpenSSL.crypto.PKCS12 (which was intended to have been deprecated at the same time as OpenSSL.crypto.load_pkcs12). ... Changed OpenSSL.crypto.X509Store.add_crl to also accept cryptography’s x509.CertificateRevocationList arguments in addition to the now deprecated OpenSSL.crypto.CRL arguments.
      » pip install pyOpenSSL
    
Published   Apr 24, 2026
Version   26.1.0
🌐
GitHub
github.com › oddcod3 › Phantom-Evasion › pull › 89
Fixed OpenSSL.crypto has no attribute PKCS12Type problem by alianjo · Pull Request #89 · oddcod3/Phantom-Evasion
November 6, 2023 - I changed changed PKCS12Type to PKCS12 cuz i had "OpenSSL.crypto has no attribute PKCS12Type problem" with python3 in kali 2020.4
Author   oddcod3
🌐
GitHub
github.com › fortra › impacket › issues › 1716
PyOpenSSL has removed deprecated PKCS12 breaking --shadow-credentials in ntlmrelayx.py · Issue #1716 · fortra/impacket
March 18, 2024 - ntlmrelayx.py -t ldaps://domain.com --shadow-credentials -smb2support --no-dump [*] Generating certificate [*] Certificate generated [*] Generating KeyCredential [*] KeyCredential generated with DeviceID: c6ec8e65-6dcf-d624-a64b-07680619cab3 [*] Updating the msDS-KeyCredentialLink attribute of ABC-123$ [*] Updated the msDS-KeyCredentialLink attribute of the target object Exception in thread Thread-7: Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1045, in _bootstrap_inner self.run() File "/home/redacted/.local/share/pipx/venvs/impacket/lib/python3.11/site-pack
Author   pwnf
Find elsewhere
🌐
GitHub
github.com › paranoidninja › CarbonCopy › issues › 18
Exception: module 'OpenSSL.crypto' has no attribute 'PKCS12Type' · Issue #18 · paranoidninja/CarbonCopy
April 2, 2024 - Exception: module 'OpenSSL.crypto' has no attribute 'PKCS12Type'#18 · Copy link · Ballistiks · opened · on Apr 2, 2024 · Issue body actions · When use the script, have the warning above. Python 3.12.2 on Windows 11 23H2 Pro for Workstations. No one assigned ·
Author   Ballistiks
🌐
Apple Developer
developer.apple.com › forums › thread › 697030
SecPKCS12Import is failing to impo… | Apple Developer Forums
$ openssl pkcs12 -info -in test.p12 Enter Import Password: MAC: sha1, Iteration 100000 MAC length: 20, salt length: 20 PKCS7 Data Shrouded Keybag: PBES2, PBKDF2, AES-256-CBC, Iteration 10000, PRF hmacWithSHA256 Bag Attributes friendlyName: cast_nearby_client_auth localKeyID: 54 69 6D 65 20 31 36 34 30 30 33 31 38 32 34 32 31 32 Key Attributes: <No Attributes> Enter PEM pass phrase: Verifying - Enter PEM pass phrase: -----BEGIN ENCRYPTED PRIVATE KEY----- MIIFHDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQIxZdIjm+Omo0CAggA ...
🌐
GitHub
github.com › NVIDIA › NVFlare › discussions › 2741
[Q&A] AttributeError: module 'cryptography.hazmat.primitives.serialization' has no attribute 'pkcs12' · NVIDIA/NVFlare · Discussion #2741
July 31, 2024 - Traceback (most recent call last): File "/anaconda/envs/nvflare-env/lib/python3.10/site-packages/nvflare/lighter/spec.py", line 174, in provision b.build(project, ctx) File "/anaconda/envs/nvflare-env/lib/python3.10/site-packages/nvflare/lighter/impl/cert.py", line 137, in build self._build_write_cert_pair(server, "server", ctx) File "/anaconda/envs/nvflare-env/lib/python3.10/site-packages/nvflare/lighter/impl/cert.py", line 119, in _build_write_cert_pair pkcs12 = serialization.pkcs12.serialize_key_and_certificates( AttributeError: module 'cryptography.hazmat.primitives.serialization' has no attribute 'pkcs12' However, if I open up a Python REPL, I can import pkcs12 from cryptography.hazmat.primitives.serialization: Python 3.10.14 (main, May 6 2024, 19:42:50) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information.
Author   NVIDIA
🌐
Pyopenssl
pyopenssl.org › en › 0.15.1 › api › crypto.html
crypto — Generic cryptographic module — pyOpenSSL 0.15.1 documentation
Returns a PKCS12 object as a string. The optional passphrase must be a string not a callback.
🌐
OpenDev
opendev.org › openstack › octavia › commit › dbe59b8b46b3457808035abc5aaadac1f9967111
When we failed to load pkcs12 cert print warning · dbe59b8b46 - octavia - OpenDev: Free Software Needs Free Tools
Print actual error when we failed to load pkcs12 cert and falling back to the default implemntation, as exception may not be related to certificate or its format like an issue with wrong methods during cryptography version mismatch *** AttributeError: module 'OpenSSL.crypto' has no attribute 'load_pkcs12' Related-Prod: PRODX-39931 Change-Id: I85c8a615c4f2e08e28939805ae0e9b2028dadaed (cherry picked from commit 96846e7b66)
🌐
Hack The Box
forum.hackthebox.com › htb content › machines
Official Certified Discussion - Page 2 - Machines - Hack The Box :: Forums
November 4, 2024 - i cant get thge nt, my pywhisker is geting this error: ./pywhisker.py -d “certified.htb” -u “judith.mader” -p ‘judith09’ --target “management_svc” --action “add” [] Searching for the target account [] Target user found: CN=management service,CN=Users,DC=certified,DC=htb [] Generating certificate [] Certificate generated [] Generating KeyCredential [] KeyCredential generated with DeviceID: dade21ea-a6e6-e6b9-022c-05b8277cd7e8 [*] Updating the msDS-KeyCredentialLink attribute of management...
🌐
GitHub
github.com › pyca › cryptography › issues › 9543
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms' · Issue #9543 · pyca/cryptography
September 5, 2023 - 4 """ 5 pyOpenSSL - A simple wrapper around the OpenSSL library 6 """ ----> 8 from OpenSSL import crypto, SSL 9 from OpenSSL.version import ( 10 __author__, 11 __copyright__, (...) 17 __version__, 18 ) 21 __all__ = [ 22 "SSL", 23 "crypto", (...) 31 "__version__", 32 ] File /usr/lib/python3/dist-packages/OpenSSL/crypto.py:3279 3259 load_pkcs12 = utils.deprecated( 3260 load_pkcs12, 3261 __name__, (...) 3266 DeprecationWarning, 3267 ) 3270 # There are no direct unit tests for this initialization.
Author   danielstankw
🌐
Ansible
docs.ansible.com › projects › ansible › latest › collections › community › crypto › openssl_pkcs12_module.html
community.crypto.openssl_pkcs12 module – Generate OpenSSL PKCS#12 archive — Ansible Community Documentation
It is not included in ansible-core. To check whether it is installed, run ansible-galaxy collection list. To install it, use: ansible-galaxy collection install community.crypto. You need further requirements to be able to use this module, see Requirements for details. To use it in a playbook, specify: community.crypto.openssl_pkcs12...
🌐
OpenVPN
support.openvpn.com › hc › en-us › articles › 30999029666843-OpenVPN-Connect-PKCS12-Import-Error-on-Windows-No-suitable-certificate-found
OpenVPN Connect PKCS12 Import Error on Windows: "No suitable certificate found" – OpenVPN Support Center
To resolve this issue, regenerate the .p12 certificate to include the "friendly name" attribute. Open a terminal with OpenSSL installed. (The steps may vary if you're using a different certificate creation tool.)
🌐
Mozilla Bugzilla
bugzilla.mozilla.org › show_bug.cgi
465926 - During import of PKCS #12 files, key usage attributes are not set correctly
At this point, NSS decrypts the private key itself and stores the key using C_CreateObject. Now however, unlike when it did C_UnwrapKey, it doesn't set any of the key usage attributes on the private key. Again, if the default values are FALSE, the private key has no key usages and all subsequent usage fails.
Top answer
1 of 1
2

Slightly modified pkcs12 creation code with key attrib is given below.

private static void createPKCS12File(String alias, PrivateKey key,
X509Certificate cert, char[] password, OutputStream pfxOut)
throws Exception
{
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(key.getEncoded());
    X509KeyUsage usage = new X509KeyUsage(X509KeyUsage.digitalSignature);
    DERSet usageSet = new DERSet(usage);
    DERSequence attrib = new DERSequence(new ASN1Encodable[]
        {new ASN1ObjectIdentifier("2.5.29.15"), usageSet});
    pki = new PrivateKeyInfo(pki.getPrivateKeyAlgorithm(),
        pki.parsePrivateKey(), new DLSet(attrib));

    OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(
        NISTObjectIdentifiers.id_aes256_CBC).setProvider("BC").build(
        password);
    PKCS12SafeBagBuilder certBuilder = new JcaPKCS12SafeBagBuilder(
        cert);
    certBuilder.addBagAttribute(
        PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(alias));

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(
        cert.getPublicKey());
    certBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute,
        pubKeyId);
    PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(pki,
        encOut);
    keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
        new DERBMPString(alias));
    keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute,
        pubKeyId);
    keyBagBuilder.addBagAttribute(new ASN1ObjectIdentifier(
        "1.3.6.1.4.1.311.17.1"),
        new DERBMPString("Microsoft Software Key Storage Provider"));
    PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();
    builder.addData(keyBagBuilder.build());
    builder.addEncryptedData(new JcePKCSPBEOutputEncryptorBuilder(
        PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC).
        setProvider("BC").build(password),
        new PKCS12SafeBag[]{certBuilder.build()});
    PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(
        NISTObjectIdentifiers.id_sha256), password);
    pfxOut.write(pfx.getEncoded(ASN1Encoding.DL));
    pfxOut.flush();
}