When the data is stored in Django's database, the best practice for security is to ensure it is stored as encrypted data. In this video, learn how to protect data in the database, and to ensure compliance, implement encryption for data-at-rest.
- To increase security, we're going to be creating a custom model field that automatically encrypts a field. The idea is that if an attacker accesses the database, they will not be able to access sensitive data without the encryption key. Right now the encryption key will be set to hello world 256. We have a special utility function called making encryption key to ensure that the key has a length of 32. The encrypt function will be taking the encoded value and then returning the encrypted value. Going to be using the encryption key with that and then calling encrypt on encoded value. So Fernet is one encryption algorithm provided by the Python cryptography library. There are other algorithms that you can choose but this one is the simplest and easiest to use for this case. And now for decryption, we're going to be again using Fernet with our same encryption key so this is symmetric encryption where we're using the same key or decrypting the value and then we have to encode it as UTF8. So now that we have these two functions, we can create our encrypted text field custom field. So we have to override from db_value which provides us with a value on expression and a connection and we just use decrypt with the value and then we have to override to Python, which provides us with a value and again we are decrypting that value and we also have to override the get_prep value method. And this will be encrypted so that when the database value is being returned and being deserialized into the field so that we can access it, we have to decrypt it and the prep value is used right before we insert it or update the database field itself. So that's where we have to encrypt it.