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

Using PyCrypto, I was able to generate public and private PEM serialization for the RSA key, but in PyCrypto the DSA class does not have an exportKey () method.

Trying PyOpenSSL I managed to create a private PEM serialization for RSA and DSA keys, bu there is no crypto.dump_publickey method in PyOpenSSL.

I am looking for a suggestion on how to generate PEM serialization for RSA and DSA keys.

Many thanks!

PS: so far I have modified the PyOpenSSL code to also export the dump_privatekey method for the cryptographic API. PyOpenSSL bug and fix can be found at: https://bugs.launchpad.net/pyopenssl/+bug/780089


I already used Twisted.conch, so I solved this problem by manually creating a DSA / RSA key using PyCrypto and then initializing the twisted.conch.ssh.key.Key file with this key. The Key class from Conch provides a toString method for serializing strings.

+6
source share
1 answer

It's unclear why you are doing this, but if all you need is a DSA private key that is compatible with openssl, you should simply run the openssl dsa (1) command in the manual page :

The DER option using the private key uses the ASN1 encoded DER form ASN.1 SEQUENCE, consisting of the values ​​version (currently zero), p, q, g, public and private key components respectively as ASN.1 INTEGER.

This is an example of 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 
+2
source

Source: https://habr.com/ru/post/887630/


All Articles