mirror of
https://github.com/jazzband/django-fernet-encrypted-fields.git
synced 2026-03-16 22:40:27 +00:00
Adding in support for multiple SALTs thus allowing them to be rotated
This commit adds in support for the SALT to be rotated by defining a list of salts within settings.py where the newer salts are added to the start.
The first key will be used to encrypt all new data, and decryption of existing values will be attempted with all given keys in order. This is useful for key rotation: place a new key at the head of the list for use with all new or changed data, but existing values encrypted with old keys will still be accessible
This is based of django-fernet-fields which is a dead package but has some useful features such as this to allow the salt to be rotated in the future for a stronger salt.
```
SALT_KEY = [
'my-newer-salt',
'the-original-salt'
]
```
This commit is contained in:
parent
c7782281dd
commit
43c0752252
1 changed files with 20 additions and 9 deletions
|
|
@ -1,22 +1,33 @@
|
|||
import base64
|
||||
from django.conf import settings
|
||||
from cryptography.fernet import Fernet
|
||||
from cryptography.fernet import Fernet, MultiFernet
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||
from django.db import models
|
||||
from django.utils.functional import cached_property
|
||||
|
||||
|
||||
class EncryptedFieldMixin(object):
|
||||
salt = bytes(settings.SALT_KEY, 'utf-8')
|
||||
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=salt,
|
||||
iterations=100000,
|
||||
backend=default_backend())
|
||||
@cached_property
|
||||
def keys(self):
|
||||
keys = []
|
||||
salt_keys = settings.SALT_KEY if isinstance(settings.SALT_KEY, list) else [settings.SALT_KEY]
|
||||
for salt_key in salt_keys:
|
||||
salt = bytes(salt_key, 'utf-8')
|
||||
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=salt,
|
||||
iterations=100000,
|
||||
backend=default_backend())
|
||||
keys.append(base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode('utf-8'))))
|
||||
return keys
|
||||
|
||||
key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode('utf-8')))
|
||||
f = Fernet(key)
|
||||
@cached_property
|
||||
def f(self):
|
||||
if len(self.keys) == 1:
|
||||
return Fernet(self.keys[0])
|
||||
return MultiFernet([Fernet(k) for k in self.keys])
|
||||
|
||||
def get_internal_type(self):
|
||||
"""
|
||||
|
|
|
|||
Loading…
Reference in a new issue