开发者

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开发者_JAVA百科 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜