I need to generate a PKCS12 file in python that will contain self-signed certificate and private key for it. I assembled the following python code for this task:
import OpenSSL
key = OpenSSL.crypto.PKey()
key.generate_key( OpenSSL.crypto.TYPE_RSA, 1024 )
cert = OpenSSL.crypto.X509()
cert.set_serial_number(0)
cert.get_subject().CN = "me"
cert.set_issuer( cert.get_subject() )
cert.gmtime_adj_notBefore( 0 )
cert.gmtime_adj_notAfter( 10*365*24*60*60 )
cert.set_pubkey( key )
cert.sign( key, 'md5' )
open( "certificate.cer", 'w' ).write(
OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) )
open( "private_key.pem", 'w' ).write(
OpenSSL.crypto.dump_privatekey( OpenSSL.crypto.FILETYPE_PEM, key ) )
p12 = OpenSSL.crypto.PKCS12()
p12.set_privatekey( key )
p12.set_certificate( cert )
open( "container.pfx", 'w' ).write( p12.export() )
This code creates a .cer file that i can view in Windows and that seems correct. It also creates a ".pfx" file that is intended to be a "PKCS#12" container with certificate and corresponding private key - a thing needed to sign executables. Unfortunately, if i try to open this ".pfx" file on Windows it fails with "file is invalid" error, and parsing it via command-line tool also fails:
certutil -asn container.pfx
Fails with "decode error" at the middle of the file.
Is it something i'm doing wrong in my code or Python + OpenSSL are not intended to create valid PKCS#12 files under Windows?
P.S. I'm using latest ActivePython 2.7 32-bit distribution.
PFX if you need to, it's the same format. If your signing tools refer to a PKCS12 file, that is the same thing as well.
Run the DigiCert® Certificate Utility for Windows (double-click DigiCertUtil). In the Certificate Export wizard, select Yes, export the private key, select pfx file, and then check Include all certificates in the certification path if possible, and finally, click Next. A . pfx file uses the same format as a .
I have an assumption, that you need to open container.pfx
in binary mode:
open( "container.pfx", 'wb' ).write( p12.export() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With