【问题标题】:Is it possible to generate correct PKCS12 (.pfx) file in Python?是否可以在 Python 中生成正确的 PKCS12 (.pfx) 文件?
【发布时间】:2012-09-17 17:55:47
【问题描述】:

我需要在 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() )

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

certutil -asn container.pfx

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

是我在代码中做错了什么还是 Python + OpenSSL 不打算在 Windows 下创建有效的 PKCS#12 文件?

附:我正在使用最新的 ActivePython 2.7 32 位发行版。

【问题讨论】:

    标签: python cryptography openssl


    【解决方案1】:

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

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

    【讨论】:

    • 非常合理的假设:)
    • 哦。再次,这个自动的“\n”翻译让我花了几个小时的工作时间:(。非常感谢!Stackoverflow 太棒了:)。
    • 我在这方面也犯了几个小时的错误!感谢您的帖子:-)
    • 我不能给你足够的投票。我还是按了几十次箭头。
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多