是否可以在Python中生成正确的PKCS12(.pfx)文件?

时间:2012-09-17 09:27:34

标签: python cryptography openssl

我需要在python中生成一个PKCS12文件,其中包含自签名证书和私钥。我为此任务汇编了以下python代码:

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

此代码创建一个.cer文件,我可以在Windows中查看,这似乎是正确的。它还创建了一个“.pfx”文件,该文件旨在成为具有证书和相应私钥的“PKCS#12”容器 - 签署可执行文件所需的东西。不幸的是,如果我尝试在Windows上打开这个“.pfx”文件,它会因“文件无效”错误而失败,并且通过命令行工具解析它也会失败:

certutil -asn container.pfx

文件中间出现“解码错误”失败。

我的代码中是否存在错误或者Python + OpenSSL无法在Windows下创建有效的PKCS#12文件?

P.S。我正在使用最新的ActivePython 2.7 32位分发。

1 个答案:

答案 0 :(得分:13)

我假设您需要以二进制模式打开container.pfx

open( "container.pfx", 'wb' ).write( p12.export() )
相关问题