Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 675
Adi Roiban Avatar asked May 09 '11 14:05

Adi Roiban


People also ask

What is key serialization?

They generally support encryption of private keys and additional key metadata. Many serialization formats support multiple different types of asymmetric keys and will return an instance of the appropriate type. You should check that the returned key matches the type your application expects when using these methods.

What is DSA and RSA keys?

RSA is a type of cryptosystem algorithm. DSA is a type of digital signature algorithm. Use. One can use the RSA algorithm for securing the transmission of data. One can use the DSA algorithm for the digital signatures and their verification.


1 Answers

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
like image 96
abbot Avatar answered Sep 30 '22 09:09

abbot