简体   繁体   English

如何为公共RSA / DSA密钥生成PEM序列化

[英]How to generate the PEM serialization for the public RSA/DSA key

Using PyCrypto I was able to generate the public and private PEM serialization for a RSA key, but in PyCrypto the DSA class has no exportKey() method. 使用PyCrypto我能够为RSA密钥生成公共和私有PEM序列化,但在PyCrypto中,DSA类没有exportKey()方法。

Trying PyOpenSSL I was able to generate the private PEM serialization for RSA and DSA keys, bu there is no crypto.dump_publickey method in PyOpenSSL. 尝试使用PyOpenSSL我能够为RSA和DSA密钥生成私有PEM序列化,但PyOpenSSL中没有crypto.dump_publickey方法。

I am looking for suggestion of how to generate the PEM serialization for RSA and DSA keys. 我正在寻找如何为RSA和DSA密钥生成PEM序列化的建议。

Many thanks! 非常感谢!

PS: meanwhile I have changed the PyOpenSSL code to also export an dump_privatekey method for crypto API. PS:同时我已经更改了PyOpenSSL代码,也为crypto API导出了dump_privatekey方法。 PyOpenSSL bug and patch can be found at: https://bugs.launchpad.net/pyopenssl/+bug/780089 PyOpenSSL错误和补丁可以在以下网址找到: https ://bugs.launchpad.net/pyopenssl/+bug/780089


I was already using Twisted.conch so I solved this problem by manually generating a DSA/RSA key using PyCrypto and then initializing a twisted.conch.ssh.key.Key using this key. 我已经在使用Twisted.conch所以我通过使用PyCrypto手动生成DSA / RSA密钥然后使用此密钥初始化twisted.conch.ssh.key.Key来解决此问题。 The Key class from Conch provides a toString method for string serialization. Conch的Key类为字符串序列化提供了toString方法。

It is not clear what you are doing this for, but if all you want is an openssl-compatible DSA private key, you should just follow the openssl dsa(1) manual page : 目前还不清楚你在做什么,但如果你想要的是一个兼容openssl的DSA私钥,你应该按照openssl dsa(1)手册页

The DER option with a private key uses an ASN1 DER encoded form of an ASN .1 SEQUENCE consisting of the values of version (currently zero), p, q, g, the public and private key components respectively as ASN .1 INTEGERs. 带有私钥的DER选项使用ASN .1 SEQUENCE的ASN1 DER编码形式,包括版本(当前为零),p,q,g,公钥和私钥组件的值,分别为ASN .1 INTEGER。

This is an example how to export/import DSA private keys in openssl format: 这是一个如何以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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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