Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you store a rsa key pair in a django model / sqlite db

i am using PyCrypto within Django (Python 2.7, Django 1.5m SQLite), i would like to create a field to store an RSAkey object. How can i do this? Converting to a string and back seems pretty error prone and since random bytes are in there, i would not trust that to be a good approach. I was able to store random keys in a charfield by base-64 encoding it (like this: Random.new().read(16).encode('base64')). But a keypair? I saw in the current dev version of Django, a binary field is incorporated, but we need to stick to 1.5.

Any help would really be appreciated.

Thanks Gerd

like image 871
Fluffy Avatar asked Apr 25 '13 13:04

Fluffy


People also ask

How do I store my RSA keys?

The best bet is probably to store it in the cryptographic library of the system that the software is running on. If you're lucky it might have a TPM or HSM that can store the key securely.

How do I create a RSA key pair?

To generate a key pair, select the bit length of your key pair and click Generate key pair. Depending on length, your browser may take a long time to generate the key pair. A 1024-bit key will usually be ready instantly, while a 4096-bit key may take up to several minutes.

What is key pair in RSA?

An RSA key pair includes a private and a public key. The RSA private key is used to generate digital signatures, and the RSA public key is used to verify digital signatures. The RSA public key is also used for key encryption of DES or AES DATA keys and the RSA private key for key recovery.


1 Answers

you just need to store the private key, because you always can generate the public key from the private one.

>>> from Crypto.PublicKey import RSA
>>> RSAkey = RSA.generate(1024)

The public key can be exported with

>>> RSAkey.publickey().exportKey()

To save the private key you might want to convert it to a text with the exportKey() method and store it in a django-TextField:

>>> RSAkey.exportKey()
'-----BEGIN RSA PRIVATE KEY-----\nMI...-----END'

Converting the text back to a RSA key object is easy too:

>>> RSA.importKey('-----BEGIN RSA PRIVATE KEY--- ....')

gets you a RSAobj like the one I generated at first.

You might also try the "hard way" by creating your own model field class, if you intend to use the functionality in other areas as well. See https://docs.djangoproject.com/en/1.5/howto/custom-model-fields/

like image 51
mawimawi Avatar answered Nov 15 '22 02:11

mawimawi