Login

Snippets by ncoghlan

Snippet List

Transparently encrypt ORM fields using OpenSSL (via M2Crypto)

Sometimes you need to store information that the server needs in unencrypted form (e.g. OAuth keys and secrets), but you don't really want to leave it lying around in the open on your server. This snippet lets you split that information into two parts: * a securing passphrase, stored in the Django settings file (or at least made available via that namespace) * the actual secret information, stored in the ORM database Obviously, this isn't as secure as using a full blown key management system, but it's still a significant step up from storing the OAuth keys directly in the settings file or the database. Note also that these fields will be displayed unencrypted in the admin view unless you add something like the following to ``admin.py``: from django.contrib import admin from django import forms from myapp.fields import EncryptedCharField class MyAppAdmin(admin.ModelAdmin): formfield_overrides = { EncryptedCharField: {'widget': forms.PasswordInput(render_value=False)}, } admin.site.register(PulpServer, PulpServerAdmin) If Django ever acquires a proper binary data type in the default ORM then the base64 encoding part could be skipped. This snippet is designed to be compatible with the use of the South database migration tool *without* exposing the passphrase used to encrypt the fields in the migration scripts. (A migration tool like South also allows you to handle the process of *changing* the passphrase, by writing a data migration script that decrypts the data with the old passphrase then writes it back using the new one). Any tips on getting rid of the current ugly prefix hack that handles the difference between deserialising unencrypted strings and decrypting the values stored in the database would be appreciated! Sources of inspiration: [AES encryption with M2Crypto](http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/) [EncryptedField snippet](http://djangosnippets.org/snippets/1095/) (helped me improve several Django-specific details)

  • fields
  • encryption
Read More

ncoghlan has posted 1 snippet.