Encryption
ormar
provides you with a way to encrypt a field in the database only.
Provided encryption backends allow for both one-way encryption (HASH
backend) as
well as both-way encryption/decryption (FERNET
backend).
Warning
Note that in order for encryption to work you need to install optional cryptography
package.
You can do it manually pip install cryptography
or with ormar by pip install ormar[crypto]
Warning
Note that adding encrypt_backend
changes the database column type to TEXT
,
which needs to be reflected in db either by migration (alembic
) or manual change
Defining a field encryption
To encrypt a field you need to pass at minimum encrypt_secret
and encrypt_backend
parameters.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Warning
You can encrypt all Field
types apart from primary_key
column and relation
columns (ForeignKey
and ManyToMany
). Check backends details for more information.
Available backends
HASH
HASH is a one-way hash (like for password), never decrypted on retrieval
To set it up pass appropriate backend value.
1 2 3 4 |
|
Note that since this backend never decrypt the stored value it's only applicable for
String
fields. Used hash is a sha512
hash, so the field length has to be >=128.
Warning
Note that in HASH
backend you can filter by full value but filters like contain
will not work as comparison is make on encrypted values
Note
Note that provided encrypt_secret
is first hashed itself and used as salt, so in order to
compare to stored string you need to recreate this steps. The order_by
will not work as encrypted strings are compared so you cannot reliably order by.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
FERNET
FERNET is a two-way encrypt/decrypt backend
To set it up pass appropriate backend value.
1 2 3 |
|
Value is encrypted on way to database end decrypted on way out. Can be used on all types, as the returned value is parsed to corresponding python type.
Warning
Note that in FERNET
backend you loose filter
ing possibility altogether as part of the encrypted value is a timestamp.
The same goes for order_by
as encrypted strings are compared so you cannot reliably order by.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Custom Backends
If you wish to support other type of encryption (i.e. AES) you can provide your own EncryptionBackend
.
To setup a backend all you need to do is subclass ormar.fields.EncryptBackend
class and provide required backend.
Sample dummy backend (that does nothing) can look like following:
1 2 3 4 5 6 7 8 9 |
|
To use this backend set encrypt_backend
to CUSTOM
and provide your backend as
argument by encrypt_custom_backend
.
1 2 3 4 5 6 7 8 9 |
|