Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generate correct PKCS12 (.pfx) file in Python?

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.

like image 248
grigoryvp Avatar asked Sep 17 '12 09:09

grigoryvp


People also ask

Is a PFX file same as PKCS12?

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.

How do I create a .PFX file from .CER certificate and private key?

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 .


1 Answers

I have an assumption, that you need to open container.pfx in binary mode:

open( "container.pfx", 'wb' ).write( p12.export() )
like image 182
Andrey Atapin Avatar answered Sep 29 '22 02:09

Andrey Atapin