Coder Social home page Coder Social logo

georgemarshall / django-cryptography Goto Github PK

View Code? Open in Web Editor NEW
380.0 17.0 75.0 249 KB

Easily encrypt data in Django

Home Page: https://django-cryptography.readthedocs.io/

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
python django

django-cryptography's Introduction

Django Cryptography

A set of primitives for easily encrypting data in Django, wrapping the Python Cryptography library. Also provided is a drop in replacement for Django's own cryptographic primitives, using Cryptography as the backend provider.

Do not forget to read the documentation.

GitHub Workflow Status (branch) Codecov branch

Cryptography by example

Using symmetrical encryption to store sensitive data in the database. Wrap the desired model field with encrypt to easily protect its contents.

from django.db import models

from django_cryptography.fields import encrypt


class MyModel(models.Model):
    name = models.CharField(max_length=50)
    sensitive_data = encrypt(models.CharField(max_length=50))

The data will now be automatically encrypted when saved to the database. encrypt uses an encryption that allows for bi-directional data retrieval.

Requirements

Installation

pip install django-cryptography

django-cryptography's People

Contributors

dependabot[bot] avatar georgemarshall avatar iurisilvio avatar mrname avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-cryptography's Issues

Django 2.0.2 and Python 3.6.0

I did exactly as in the example,

I even tried with a default value
test_encrypt = encrypt(models.CharField(max_length=300,default="test_me"))

However when I look in the database its just stored as text

Support for rotation of secrets

Hi everyone,

we accidentally leaked the SECRET_KEY of a test environment that was used for decrypting model fields using this library. In such a case, to be on the safe side, one has to rotate the leaked key. While I am aware that we can run a migration similar to this one here it would be great if django-cryptography would has an officially supported way how to rotate encryption keys:

Proposal A)
Ship a Django command to perform such a secret rotation:

$ django-admin rotate_encryption_key <current secret key> <new secret key> 

Afterwards the settings.py needs to be adjusted to reference the new key.

Proposal B)
If Proposal A is hard to implement, an easier but less secure alternative option would be to support two kinds of secret specifications:

  • a secret used for encryption (i.e. SECRET_KEY or CRYPTOGRAPHY_KEY as used today)
  • a list of secrets used for decryption (e.g. CRYPTOGRAPHY_PREVIOUS_KEYS=['foo', 'bar'])

In case a field cannot be decrypted using either SECRET_KEY or CRYPTOGRAPHY_KEY all secrets in CRYPTOGRAPHY_PREVIOUS_KEYS are tried in order. This would enable us to at lest have all new secrets encrypted with a new key, while the encryption of other fields is still supported.

Thanks!

How to use HA1 field ?

How can I use your app to do this function

echo -n "username:realm:password" | md5sum

the 2 ist element is a field and the last one is the password

Using unique=True on MySQL fails due to missing "key length"

When creating (in a migration) an encrypted field that has unique=True, the MySQL backend gives the following error:

MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'email_new' used in key specification without a key length")

This SO post explains the reason behind the error: https://stackoverflow.com/a/1827099/1791183

1, Is this something that django-cryptography can fix?
2. Will unique=True even work on an encrypted field?
3. Is there a workaround?

Json fields

This doesn't work for Json fields... can you propose a solution?

Django 3.0 Import Error

Summary:
Django 3.0 cannot import name six. Can you update the package to use the new six package?

Similar: Django 3.0 Six - SO

Traceback:
File "\app\src\core\main\api\vevnp\lib\site-packages\django_cryptography\fields.py", line 6, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (\src\core\main\api\vevnp\lib\site-packages\django\utils\__init__.py) (vevnp)

Accessing data from two Django Applications

I am encrypting data in a few CharFields, and attempting to read this data from two different Django applications. I have specified the same CRYPTOGRAPHY_KEY and CRYPTOGRAPHY_SALT in the settings files of each application. However I am unable to decrypt the data in the second application unless I use the same SECRET_KEY value in both applications. It was my impression that CRYPTOGRAPHY_KEY would take precedence over SECRET_KEY.

This seems to indicate only the key specified on the field or the SECRET_KEY is used.

class FernetSigner(Signer):
    version = b'\x80'

    def __init__(self, key=None):
        """
        :type key: any
        :rtype: None
        """
        self.digest = hashes.SHA256()
        self.key = force_bytes(key or settings.SECRET_KEY)

Am I misunderstanding how to configure the applications so that they can both access the data?

Add support for PyCryptodome

Add PyCryptodome as an alternative to Cryptography. Additionally consider making PyCryptodome the default implementation.

Advantages:

  • Doesn't use OpenSSL
  • No FFI binding like Cryptography
  • More cryptographic algorithms including elliptic curve variants.

Disadvantages:

  • Not as many followers (less eyes on code for auditing)

Could not encripte custom auth user email field

I have modified django auth to use email as my username. I need to save the email encripted using django-cryptography. I tried to use encrypt function in email field in my model.py. but it throws me the below error

django.core.exceptions.FieldError: Unsupported lookup 'exact' for EncryptedEmailField or join on the field not permitted, perhaps you meant exact or iexact?

I get this error when i create superuser and register new user.

Problem encrypting an IntegerField when using PostresSQL

Python 3.6.6
Django 2.0.6
django-cryptography 0.3

I can create encrypted IntegerFields just fine when using sqlite as my db backend, but when I switch to using PSQL I get the following when I runserver:

Performing system checks...

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fae83dcabf8>
Traceback (most recent call last):
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check(display_num_errors=True)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
    errors.extend(model.check(**kwargs))
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/base.py", line 1200, in check
    errors.extend(cls._check_fields(**kwargs))
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/base.py", line 1272, in _check_fields
    errors.extend(field.check(**kwargs))
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django_cryptography/fields.py", line 126, in check
    errors = super(EncryptedMixin, self).check(**kwargs)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1785, in check
    errors = super().check(**kwargs)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 207, in check
    errors.extend(self._check_validators())
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 308, in _check_validators
    for i, validator in enumerate(self.validators):
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1807, in validators
    min_value, max_value = connection.ops.integer_field_range(internal_type)
  File "/home/pstiverson/.virtualenvs/Money-Positive/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 600, in integer_field_range
    return self.integer_field_ranges[internal_type]
KeyError: 'BinaryField'

I get a similar error when I try database migrations:

Traceback (most recent call last):
  File "./manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
    self.check()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
    issues.extend(super()._run_checks(**kwargs))
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
    errors.extend(model.check(**kwargs))
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 1200, in check
    errors.extend(cls._check_fields(**kwargs))
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 1272, in _check_fields
    errors.extend(field.check(**kwargs))
  File "/app/.heroku/python/lib/python3.6/site-packages/django_cryptography/fields.py", line 126, in check
    errors = super(EncryptedMixin, self).check(**kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1785, in check
    errors = super().check(**kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 207, in check
    errors.extend(self._check_validators())
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 308, in _check_validators
    for i, validator in enumerate(self.validators):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1807, in validators
    min_value, max_value = connection.ops.integer_field_range(internal_type)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 600, in integer_field_range
    return self.integer_field_ranges[internal_type]
KeyError: 'BinaryField'

This seems like a shortcoming of the postgres db backend, but I thought I would report it here in case there is anything that can be done about it.

Edit: using a DecimalField with decimal_place=0 is a pretty suitable workaround.

SQL query to decrypt field

Hi,
I'm generating some reports with data obtained via SQL queries but now some of this fields are encrypted because of client request. I would like to know if it's possible to build a query to obtain the decrypted value of an encrypted field.
Thanks

Decrypting fields manually from querying the db?

Hi, I would like to know how to decrypt fields manually from querying the database directly. I am using MySQL and the MySQL CLI.

For example, this is the content of the encrypted field:

� ap�s��vdV8\� �P5�-X�9�m��cB,j�"������> ����j�~0����zah |�_�������H��

I am using https://asecuritysite.com/encryption/ferdecode to decode it (using my secret key) but I get no output.

Thanks

How to get the encrypted fields in django admin?

I have successfully encrypted data and I have confirmed it after checking the tables.
But when I view the data in django admin interface, it comes out as plain text most probably because of the bi-directional nature of the encrypt wrapper.
Is there any way to override this nature and display encrypted data in the django admin.

Supported lookups

Hi, it seems as though this package only supports the isnull lookup. Is there any plan to support additional lookups? I would specifically request an iexact lookup.

Accessing encrypted data

Is there any way to access the encrypted data?
I need to move it between systems, and it seems safer to keep it encrypted while in transit, and then insert it directly in the new system (which must have the same key, of course).
I could work around this by making an extra raw SQL query, but that seems like an awful way of doing it.

RemovedInDjango40Warning

Using this lib yields:

RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). description = _("Pickled data")

While using Django 3.0+

Ecrypted field doesn't work with Docker

I get this error always I put my app on docker:

django.core.signing.BadSignature: Signature "b'w+bTViO2BmaCq0+oUvviyZVeRvPOHtVizIj+jQqUsxE=\n'" does not match

Complete error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/core/signing.py", line 237, in unsign
    self.signature(signed_value[:-d_size]).verify(sig)
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
    ctx.verify(signature)
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
    return Response(serializer.data)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 760, in data
    ret = super().data
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 677, in to_representation
    return [
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 72, in __iter__
    for row in compiler.results_iter(results):
  File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1086, in apply_converters
    value = converter(value, expression, connection)
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/fields.py", line 173, in from_db_value
    return self._load(force_bytes(value))
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/fields.py", line 115, in _load
    return pickle.loads(self._fernet.decrypt(value, self.ttl))
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/utils/crypto.py", line 143, in decrypt
    data = self._signer.unsign(data, ttl)
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/core/signing.py", line 239, in unsign
    raise BadSignature(
django.core.signing.BadSignature: Signature "b'w+bTViO2BmaCq0+oUvviyZVeRvPOHtVizIj+jQqUsxE=\n'" does not match
ERROR:django.request:Internal Server Error: /api/v3/upload/document
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/core/signing.py", line 237, in unsign
    self.signature(signed_value[:-d_size]).verify(sig)
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
    ctx.verify(signature)
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
    return Response(serializer.data)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 760, in data
    ret = super().data
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 677, in to_representation
    return [
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 72, in __iter__
    for row in compiler.results_iter(results):
  File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1086, in apply_converters
    value = converter(value, expression, connection)
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/fields.py", line 173, in from_db_value
    return self._load(force_bytes(value))
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/fields.py", line 115, in _load
    return pickle.loads(self._fernet.decrypt(value, self.ttl))
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/utils/crypto.py", line 143, in decrypt
    data = self._signer.unsign(data, ttl)
  File "/usr/local/lib/python3.8/site-packages/django_cryptography/core/signing.py", line 239, in unsign
    raise BadSignature(
django.core.signing.BadSignature: Signature "b'w+bTViO2BmaCq0+oUvviyZVeRvPOHtVizIj+jQqUsxE=\n'" does not match

BLAKE2b Throws Error

Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 29 2018, 20:59:26)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
django==1.11.15
django-cryptography==0.3
cryptography==2.3.1

settings.py

import cryptography.hazmat.primitives.hashes
CRYPTOGRAPHY_DIGEST = cryptography.hazmat.primitives.hashes.BLAKE2b
Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models()
  File "lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "xxxx/models.py", line 11, in <module>
    from django_cryptography.fields import encrypt
  File "lib/python2.7/site-packages/django_cryptography/fields.py", line 10, in <module>
    from django_cryptography.core.signing import SignatureExpired
  File "lib/python2.7/site-packages/django_cryptography/core/signing.py", line 20, in <module>
    from ..utils.crypto import constant_time_compare, salted_hmac
  File "lib/python2.7/site-packages/django_cryptography/utils/crypto.py", line 12, in <module>
    from ..conf import CryptographyConf
  File "lib/python2.7/site-packages/django_cryptography/conf.py", line 9, in <module>
    class CryptographyConf(AppConf):
  File "lib/python2.7/site-packages/appconf/base.py", line 74, in __new__
    new_class._configure()
  File "lib/python2.7/site-packages/appconf/base.py", line 105, in _configure
    cls._meta.configured_data = obj.configure()
  File "lib/python2.7/site-packages/django_cryptography/conf.py", line 32, in configure
    backend=backend,
  File "lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py", line 25, in __init__
    if not backend.pbkdf2_hmac_supported(algorithm):
  File "lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 276, in pbkdf2_hmac_supported
    return self.hmac_supported(algorithm)
  File "lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 192, in hmac_supported
    return self.hash_supported(algorithm)
  File "lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 187, in hash_supported
    name = self._build_openssl_digest_name(algorithm)
  File "lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 179, in _build_openssl_digest_name
    algorithm.name, algorithm.digest_size * 8
TypeError: Error when calling the metaclass bases
    unsupported operand type(s) for *: 'property' and 'int'

Upgrade results in InvalidSignature: Signature did not match digest.

Hi,
I'm experiencing a problem accessing existing encrypted data after upgrading django-cryptotgraphy and Django.

cryptography==2.7
Django==2.2.7
django-cryptography==0.3
Python 3.6.3

to this:

cryptography==3.4.7
Django==3.2
django-cryptography==1.0
Python 3.6.9

The two installations exist independently, and are accessing the same database, with the same CRYPTOGRAPHY_KEY. The first one still works. The second one throws this error when trying to access that model:

Traceback (most recent call last):
  File "/home/liam/.virtualenvs/myapplication/lib/python3.6/site-packages/django_cryptography/core/signing.py", line 237, in unsign
    self.signature(signed_value[:-d_size]).verify(sig)
  File "/home/liam/.virtualenvs/myapplication/lib/python3.6/site-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
    ctx.verify(signature)
  File "/home/liam/.virtualenvs/myapplication/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

Is it possible something changed in the cryptography package? Any suggestions on where to look?

Thanks for any tips.

Error when saving Data

Unsupported lookup 'exact' for EncryptedCharField or join on the field not permitted, perhaps you meant exact or iexact?

Django 3.2 incompatible

Django 3.2 implemented signer.sign_object, that fails with django-cryptography TimestampSigner.

To reproduce, call messages.error(request, 'foo') in a request.

Traceback (most recent call last):
  File "django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "django/utils/deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "django/contrib/messages/middleware.py", line 23, in process_response
    unstored_messages = request._messages.update(response)
  File "django/contrib/messages/storage/base.py", line 128, in update
    return self._store(messages, response)
  File "django/contrib/messages/storage/fallback.py", line 48, in _store
    messages = storage._store(messages, response, remove_oldest=False)
  File "django/contrib/messages/storage/cookie.py", line 124, in _store
    encoded_data = self._encode(messages)
  File "django/contrib/messages/storage/cookie.py", line 165, in _encode
    return self.signer.sign_object(messages, serializer=MessageSerializer, compress=True)
AttributeError: 'TimestampSigner' object has no attribute 'sign_object'

Does not support Django 3.0

In 3.0 django.utils.six has been dropped and they recommend switching to the standard six lib. When trying run the manage.py collectstatic command the following exception is thrown.

File "/root/.local/lib/python3.6/site-packages/django_cryptography/fields.py", line 6, in
from django.utils import six
ImportError: cannot import name 'six'

Migrate existing database

Hello,

Have you an idea how I can migrate an existing database in order to user django-cryptography ?

I am planning to use it in a existing database. Currently the migration only convert charfield to blob but do not encrypt the data.

I am searching to do it manually but right now I do not have a solution.

Accessing encrypted fields

Hi, im using Graphene, i have a model that has some encrypted fields, now from my schema i want to do seach/look-up or filters in one of the encrypted fields how can i view that encrypted data?

Q Query

I have following model:

class Adressen(models.Model):
geburtsdatum = encrypt(models.DateField(default=None,blank=True,null=True))

views:
start = date.today()
end = start + timedelta(days=14)
Geburtstage = Adressen.objects.filter(
Q(geburtsdatum__month=start.month) & Q(geburtsdatum__day__gte=start.day) |
Q(geburtsdatum__month=end.month) & Q(geburtsdatum__day__lte=end.day)
).order_by('geburtsdatum')

Exception:

django.core.exceptions.FieldError: Unsupported lookup 'month' for EncryptedDateField or join on the field not permitted, perhaps you meant month?

Remove encryption

Hello,
We've been using this package in the fields of a model, but we want to remove encryption from some fields now cause we need to do search lookups. I'm wondering which is the best way to do this. Would it be enough just removing encrypt() from model fields and run makemigrations/migrate? I Guess data will remain encrypted into the DB.

I was thinking in writting some custom migrations like this:
1.- Given field_x is encrypted, add another field field_x_text to the model
2.- Read data from field_x to get unencrypted value and write it in field_x_text
3- Remove field_x
4.- Rename field_x_text to field_x

Any advice would be appreciated. Thanks

Decryption of Encrypted Fields with Django Project hosted on Heroku

Hi there!

I am new to django-cryptography and have read the documentation and was wondering about the following question:

Before I migrate my data, I want to make sure everything would work as expected. I am hosting my project on Heroku. I know that Heroku rotates the servers and rotates the server on every rebuild as well. I don't know enough about how this library works behind the scenes to understand whether the following could happen or not so I am sorry for my uninformed question. Will the new servers that Heroku attaches to my project still be able to decrypt the encrypted fields?

I have noticed that when I access my data through the Django admin site but not on the same machine I migrated dummy data to be encrypted, that it says <memory at 0x0x0x0x0x0x>. Just from curiosity and intrest, would you encrypt large amounts of data with this library or would that be not the ideal case?

Thanks so much in advance!

Encryption using client-specific keys

Hi. I am looking for a way to encrypt a particular field in a model using different keys. The model has data owned by multiple clients and each client has their own keys. Has the library been used for a similar use case before? Do you have any thoughts on how this could be done?

In a clone branch, I was thinking of changing _encryption_key in FernetBytes.__init__ method to get the key from a different method instead of from settings. Will this work?

django 2.0 python3.5

[root@111 autoops]# python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in
execute_from_command_line(sys.argv)
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/init.py", line 371, in execute_from_command_line
utility.execute()
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/init.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/python3/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/python3/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/python3/lib/python3.5/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
errors.extend(model.check(**kwargs))
File "/usr/local/python3/lib/python3.5/site-packages/django/db/models/base.py", line 1200, in check
errors.extend(cls._check_fields(**kwargs))
File "/usr/local/python3/lib/python3.5/site-packages/django/db/models/base.py", line 1272, in _check_fields
errors.extend(field.check(**kwargs))
File "/usr/local/python3/lib/python3.5/site-packages/django_cryptography/fields.py", line 130, in check
if getattr(self, 'remote_field', self.rel):
AttributeError: 'EncryptedCharField' object has no attribute 'rel'

Working with OTP

How is this work when we use OTP from 3rd party like Twilio or something? Still work doesn't it?

Raising Exception: Bad Signature, When i am trying to get the data from encrypted field.

Hello all,

Encryption part in models going good, but when i start filtering data by a non-encrypted field i am geting bad signature exception. What am i missing here.

My Modal

class MyModal(models.Model):
    name = encrypt(models.CharField(max_length=50))
    area = models.CharField(max_length=50)

My Code:

from models import MyModal

def myFunc():
    data_list = MyModal.objects.filter(area='myarea')
    for data in data_list:
        print data.id
    return data.id

Is there anything i am missing?

IP address Encrypted

Hello,

I face this issue

django.db.utils.ProgrammingError: cannot cast type inet to bytea
LINE 1: ...access" ALTER COLUMN "ac_ip" TYPE bytea USING "ac_ip"::bytea

When i try to encrypt an ipaddress field :

ac_ip = encrypt(models.GenericIPAddressField(
        verbose_name="IP", protocol='IPv4', blank=True, null=True))

Anyway to workaround this ?

Thanks for your help.

Regards,

Thierry

Migrations generating duplicates in Django 1.11

I'm using this library for a single field as such:

class Account(models.Model):
    address = models.EmailField(blank=True)
    password = encrypt(models.CharField(max_length=128, blank=True))

When I run ./manage.py makemigrations, it generates a new migration for this model, even though I've already generated and ran the migration for this model.

 ./manage.py makemigrations
Migrations for 'accounts':
  audit/accounts/migrations/0007_auto_20171016_2125.py
    - Alter field password on account
 ./manage.py makemigrations
Migrations for 'accounts':
  audit/accounts/migrations/0008_auto_20171016_2128.py
    - Alter field password on account
 ./manage.py makemigrations
Migrations for 'accounts':
  audit/accounts/migrations/0009_auto_20171016_2128.py
    - Alter field password on account

Each migration contains the same content:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-10-16 21:25
from __future__ import unicode_literals

from django.db import migrations, models
import django_cryptography.fields


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0006_auto_20171014_0122'),
    ]

    operations = [
        migrations.AlterField(
            model_name='account',
            name='password',
            field=django_cryptography.fields.encrypt(models.CharField(verbose_name=models.CharField(verbose_name=models.CharField(blank=True, max_length=128)))),
        ),
    ]

Any idea what might be up here and how to solve it?

SECRET_KEY is still used for some calculations even if CRYPTOGRAPHY_KEY is set

Per the documentation,

CRYPTOGRAPHY_KEY
Default: None
When value is None a key will be derived from SECRET_KEY. Otherwise the value will be used for the key.

This documentation is incorrect, or at least incomplete. I can confirm that even when CRYPTOGRAPHY_KEY is set, some calculations still use SECRET_KEY. This can be demonstrated by populating some encrypted fields, then changing SECRET_KEY - a BadSignature error will be reported on trying to access the fields, but changing SECRET_KEY back to its old value will restore normal operation.

BadSignature('Signature is not valid')

After installation & adding to model

class SomeModel(models.Model):
    email = encrypt(models.EmailField())

raises next error

Traceback (most recent call last):
  File "XXX/env/lib/python3.7/site-packages/django_cryptography/core/signing.py", line 223, in unsign
    version, timestamp, value, sig = struct.unpack(fmt, signed_value)
struct.error: bad char in struct format

During handling of the above exception, another exception occurred:

XXX/env/lib/python3.7/site-packages/django_cryptography/core/signing.py", line 225, in unsign
    raise BadSignature('Signature is not valid')

encrypt() function is not encrypting my data

So i started using django-cryptography to store sensible data, i am using the encrypt function and passing a models.Charfield argument as the field to encrypt, every thing works fine, no errors, no warning, but when i check my data in the django admin page, i see the raw text, no data was encrypted, as i know i followed all the steps, i don't know if i missed any minimal step.

Python 3.7.2
Django 2.2.12
django-cryptography 1.0

from django_cryptography.fields import encrypt

class EncryptedFieldModel(models.Model)
encrypted_field = encrypt(models.Charfield(max_length=100))

Django-3.1 not supported?

The tests do not cover Django-3.1, is it not supported?
Although it is somehow early, I have the same question for Python-3.9.

django.core.signing.BadSignature: Signature is not valid

I got this when I logged in on the admin and checked the newsletter signups, it returned

BadSignature at /admin/sendemail/newsletteruser/ Signature is not valid

This is the whole traceback on the CLI

Internal Server Error: /admin/sendemail/newsletteruser/
Traceback (most recent call last):
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/core/signing.py", line 223, in unsign
version, timestamp, value, sig = struct.unpack(fmt, signed_value)
struct.error: bad char in struct format

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1790, in changelist_view
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/query.py", line 256, in __len__
self._fetch_all()
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/query.py", line 72, in __iter__
for row in compiler.results_iter(results):
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1044, in apply_converters
value = converter(value, expression, connection)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/fields.py", line 180, in from_db_value
return self._load(force_bytes(value))
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/fields.py", line 121, in _load
return pickle.loads(self._fernet.decrypt(value, self.ttl))
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/utils/crypto.py", line 143, in decrypt
data = self._signer.unsign(data, ttl)
  File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/core/signing.py", line 225, in unsign
raise BadSignature('Signature is not valid')
django.core.signing.BadSignature: Signature is not valid
"GET /admin/sendemail/newsletteruser/ HTTP/1.1" 500 144750

What does this mean? What do I need to show?

Unable to search/query on fields that uses django-cryptography

Hey there, I am making Note apps which store people's notes. Now, I have used a text field on the Note model. Now, if someone on-page, is supposed to search for 'keyword' then getting the following error appears-
Unsupported lookup 'icontains' for EncryptedTextField or join on the field not permitted, perhaps you meant icontains or contains?

Here is the queryset which I have used-
queryset = Note.objects.filter( Q(title__icontains=query) | Q(tags__name__icontains=query) | Q(text__icontains=query) ).distinct()

Here is the particular field from the model-
text = encrypt(models.TextField(null=True,blank=True))

Encrypting ForeignKeys

How do I encrypt ForeignKey fields? I have tried something like this:

medicine = encrypt(models.ForeignKey(to='assessment.Medication', on_delete=models.CASCADE))

But I am getting errors which is encountered during circular import.

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

  • Django 2.2.13
  • Python 3.8
  • django-cryptography 1.0

Full error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[1]
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute
    autoreload.check_errors(django.setup)()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/torsho/employeeHealthAssessmentApp/assessment/models.py", line 199, in <module>
    class Prescription(models.Model):
  File "/home/torsho/employeeHealthAssessmentApp/assessment/models.py", line 209, in Prescription
    medicine = encrypt(models.ForeignKey(to='assessment.models.Medication', on_delete=models.CASCADE))
  File "/home/torsho/employeeHealthAssessmentApp/django_cryptography/fields.py", line 216, in encrypt
    name, path, args, kwargs = base_field.deconstruct()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 856, in deconstruct
    name, path, args, kwargs = super().deconstruct()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 583, in deconstruct
    swappable_setting = self.swappable_setting
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 374, in swappable_setting
    return apps.get_swappable_settings_name(to_string)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 288, in get_swappable_settings_name
    for model in self.get_models(include_swapped=True):
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 178, in get_models
    self.check_models_ready()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 140, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[1]
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute
    autoreload.check_errors(django.setup)()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/torsho/employeeHealthAssessmentApp/assessment/models.py", line 199, in <module>
    class Prescription(models.Model):
  File "/home/torsho/employeeHealthAssessmentApp/assessment/models.py", line 209, in Prescription
    medicine = encrypt(models.ForeignKey(to='assessment.models.Medication', on_delete=models.CASCADE))
  File "/home/torsho/employeeHealthAssessmentApp/django_cryptography/fields.py", line 216, in encrypt
    name, path, args, kwargs = base_field.deconstruct()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 856, in deconstruct
    name, path, args, kwargs = super().deconstruct()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 583, in deconstruct
    swappable_setting = self.swappable_setting
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 374, in swappable_setting
    return apps.get_swappable_settings_name(to_string)
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 288, in get_swappable_settings_name
    for model in self.get_models(include_swapped=True):
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 178, in get_models
    self.check_models_ready()
  File "/home/torsho/employeeHealthAssessmentApp/env/lib/python3.8/site-packages/django/apps/registry.py", line 140, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Error accessing the encrypt fields.

Data got encrypted when I created a field wrapping with encrypt method. But when I access any obj.field a Value Error is raised.
ValueError: Invalid padding bytes

Which in turn raises
django_cryptography.utils.crypto.InvalidToken

Django==3.0.7
djangorestframework==3.11.0
cryptography==3.1
django-cryptography==1.0

Django 3.0 Compatibility

Not that it is a rush or anything, but while running tests that require data migrations, the following warning is thrown:

usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py:995: RemovedInDjango30Warning: Remove the context parameter from EncryptedCharField.from_db_value(). Support for it will be removed in Django 3.0. RemovedInDjango30Warning

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.