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

拈花ヽ惹草 提交于 2019-12-06 02:02:21

问题


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.

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.

I am looking for suggestion of how to generate the PEM serialization for RSA and DSA keys.

Many thanks!

PS: meanwhile I have changed the PyOpenSSL code to also export an dump_privatekey method for crypto API. PyOpenSSL bug and patch can be found at: 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. The Key class from Conch provides a toString method for string serialization.


回答1:


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:

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.

This is an example how to export/import DSA private keys in openssl format:

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


来源:https://stackoverflow.com/questions/5938664/how-to-generate-the-pem-serialization-for-the-public-rsa-dsa-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!