Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving RSA keys to a file, using pycrypto

I’m using PyCrypto 2.3 and I would like to save the keys I have generated into a file, so as to distribute them to the client and server. I can’t seem to find a way to print the keys correctly, neither can I find examples on the internet.

    def resetKeys(self):
        keys = RSA.generate(1024)

        privHandle = open(self.privateKeyFile, 'wb')
        privHandle.write(keys.privatekey())
        privHandle.close()

        pubHandle = open(self.publicKeyFile, 'wb')
        pubHandle.write(keys.publickey())
        pubHandle.close()

This codes does not work for many reasons: first, keys.publickey() doesn’t seem to be printable, it returns:

    <_RSAobj @0x10f810d0 n(1024),e>

and second, keys has no function named privatekey.

Has anyone done that before?

like image 298
qdii Avatar asked Feb 08 '12 16:02

qdii


People also ask

How do I import an RSA key?

You can use the Aspnet_regiis.exe tool with the –pi switch to import an RSA key container from an XML file. You must also specify whether the imported key container is a machine-level or user-level key container.

What is the file format of RSA private key?

PEM. This format can contain private keys (RSA or DSA), public keys (RSA or DSA) and X. 509 certificates. It is the default format for OpenSSL.


2 Answers

keys.exportKey() for the private key, keys.publickey().exportKey() for the public key. You can change the output format with format argument, see the docs at this site.

like image 198
wRAR Avatar answered Sep 30 '22 02:09

wRAR


The following piece of code will create the RSA key pair and store them in PEM files as well as print them.

Original credits : wRAR from this post & AJ poultier from [pyOpenSSL creating a pem file

from Crypto.PublicKey import RSA
private_key = RSA.generate(1024)
public_key = private_key.publickey()
print(private_key.exportKey(format='PEM'))
print(public_key.exportKey(format='PEM'))

with open ("private.pem", "w") as prv_file:
    print("{}".format(private_key.exportKey()), file=prv_file)

with open ("public.pem", "w") as pub_file:
    print("{}".format(public_key.exportKey()), file=pub_file)
like image 41
KARAN SHAH Avatar answered Sep 30 '22 00:09

KARAN SHAH