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
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With