【问题标题】:How to generate the PEM serialization for the public RSA/DSA key如何为公共 RSA/DSA 密钥生成 PEM 序列化
【发布时间】:2011-05-09 14:56:30
【问题描述】:

使用 PyCrypto,我能够为 RSA 密钥生成公共和私有 PEM 序列化,但在 PyCrypto 中,DSA 类没有 exportKey() 方法。

尝试 PyOpenSSL 我能够为 RSA 和 DSA 密钥生成私有 PEM 序列化,但是 PyOpenSSL 中没有 crypto.dump_publickey 方法。

我正在寻找有关如何为 RSA 和 DSA 密钥生成 PEM 序列化的建议。

非常感谢!

PS:同时我已经更改了 PyOpenSSL 代码以导出加密 API 的 dump_privatekey 方法。 PyOpenSSL 错误和补丁可以在:https://bugs.launchpad.net/pyopenssl/+bug/780089


我已经在使用 Twisted.conch,所以我通过使用 PyCrypto 手动生成 DSA/RSA 密钥,然后使用该密钥初始化一个 twisted.conch.ssh.key.Key 解决了这个问题。 Conch 的 Key 类为字符串序列化提供了一个 toString 方法。

【问题讨论】:

    标签: python openssl pycrypto pyopenssl


    【解决方案1】:

    不清楚你这样做是为了什么,但如果你想要的只是一个与 openssl 兼容的 DSA 私钥,你应该按照 openssl dsa(1) manual page

    带有私钥的 DER 选项使用 ASN .1 的 ASN1 DER 编码形式 SEQUENCE 的值组成 版本(当前为零),p,q,g, 公钥和私钥组件 分别作为 ASN .1 INTEGERs。

    这是一个如何以 openssl 格式导出/导入 DSA 私钥的示例:

    from Crypto.PublicKey import DSA
    from Crypto.Util import asn1
    
    key = DSA.generate(1024)
    
    # export
    
    seq = asn1.DerSequence()
    seq[:] = [ 0, key.p, key.q, key.g, key.y, key.x ]
    
    exported_key = "-----BEGIN DSA PRIVATE KEY-----\n%s-----END DSA PRIVATE KEY-----" % seq.encode().encode("base64")
    
    print exported_key
    
    # import
    
    seq2 = asn1.DerSequence()
    data = "\n".join(exported_key.strip().split("\n")[1:-1]).decode("base64")
    seq2.decode(data)
    p, q, g, y, x = seq2[1:]
    
    key2 = DSA.construct((y, g, p, q, x))
    
    assert key == key2
    

    【讨论】:

    • 感谢您提供的宝贵示例。我只想从 Python 生成密钥对,以便它们可以与 OpenSSH 一起使用。我在看公钥部分。对于公钥,我认为我需要 SubjectPublicKeyInfo 因为这是我从手册页 When used with a public key it uses a SubjectPublicKeyInfo structure: it is an error if the key is not DSA. 中读到的内容,再次感谢!
    • 我在 Twisted 代码中找到了公钥格式:twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/…
    • 在这种情况下,您可能应该与paramiko 来源核实。
    • 现在 Twisted.conch.ssh.key 解决了我的问题。你的回答并没有直接解决我的问题,但它给了我一个好的开始和动力去寻找文档:)
    • keyczarkeyczar.util中有一些更详细的转换例程
    猜你喜欢
    • 2013-05-07
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2023-01-14
    • 2022-08-10
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多