5

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

4

1 回答 1

10

您只需要存储私钥,因为您始终可以从私钥生成公钥。

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

公钥可以导出

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

要保存私钥,您可能希望使用该exportKey()方法将其转换为文本并将其存储在 django-TextField 中:

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

将文本转换回 RSA 密钥对象也很容易:

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

为您提供一个 RSAobj,就像我最初生成的一样。

如果您还打算在其他领域使用该功能,您也可以通过创建自己的模型字段类来尝试“艰难的方式”。请参阅https://docs.djangoproject.com/en/1.5/howto/custom-model-fields/

于 2013-04-25T14:33:45.780 回答