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.