简体   繁体   中英

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?

PS I'm using latest ActivePython 2.7 32-bit distribution.

我有一个假设,你需要以二进制模式打开container.pfx

open( "container.pfx", 'wb' ).write( p12.export() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM