'Get the encrypted value in django-fernet-fields

I use the django-fernet-fields library:

class RoutePoint(models.Model):
    username = models.CharField(max_length=30)
    password = EncryptedCharField(max_length=30, null=True)

When I access an encrypted field, the value of the field is automatically decrypted.

p = RoutePoint.objects.all()[0]
print(p.password)
> mypass

Is there any way I can get the encrypted value that is actually stored in the database?



Solution 1:[1]

The method that performs the decryption within the model.Field is def from_db_value(self, value, expression, connection, *args). In theory, you could override this method for RoutePoint.password and have it return a tuple, with the first element being the raw field value and the second being the decrypted plaintext.

Here is a pointer to the relevant source code https://github.com/orcasgit/django-fernet-fields/blob/master/fernet_fields/fields.py#L74.

Note: django-fernet-fields hasn't been updated in over 3 years, and as a previous user myself, I forked the codebase to one that is backed by Google Tink instead https://github.com/script3r/django-tink-fields

Solution 2:[2]

Use next() instead of nextLine(). nextLine() reads inputs including the space between the words. A space will be read as empty String. If you are using next(), it will not read blank lines at all. It reads the input till the space.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Isaac E
Solution 2 Optimizer