Encrypting Sensitive Data¶
This section describes how Ming can be used to automatically encrypt and decrypt your document’s fields. This is accomplished by leveraging MongoDB’s Client-Side Field Level Encryption (CSFLE) feature.
Encryption at the Foundation Level¶
When declaratively working with models by subclassing Document
in the Ming Foundation Layer, you can add field level encryption by pairing a DecryptedField
with a Field
.
A simple example might look like the following.
class UserEmail(Document):
class __mongometa__:
session = session
name = 'user_emails'
_id = Field(schema.ObjectId)
email_encrypted = Field(S.Binary, if_missing=None)
email = DecryptedField(str, 'email_encrypted')
Breaking down DecryptedField¶
This approach requires that you follow a few conventions:
The field storing the encrypted data should be configured in the following way:
Next to this should be a corresponding
DecryptedField
that will decrypt the data.Its first argument should be the type that you expect the decrypted data to be (str, int, etc.).
The second argument should be the name of the encrypted field (e.g. email_encrypted).
The DecryptedField’s name should be the same as the encrypted
Field
, but without the _encrypted suffix (e.g. email).
Encryption at the Declarative Level¶
Similarly when working with the higher level of abstraction offered by DecryptedProperty
with a FieldProperty
A simple example might look like the following.
class UserEmail(MappedClass):
class __mongometa__:
session = session
name = 'user_emails'
_id = FieldProperty(schema.ObjectId)
email_encrypted = FieldProperty(S.Binary, if_missing=None)
email = DecryptedProperty(str, 'email_encrypted')
Breaking down DecryptedProperty¶
Similarly to the foundation level, this approach requires that you follow a few conventions:
The field storing the encrypted data should be configured in the following way:
It should be a
FieldProperty
.The FieldProperty should be of type
Binary
.The FieldProperty’s name should end with _encrypted.
Next to this should be a
DecryptedProperty
that will decrypt the data.Its first argument should be the type that you expect the decrypted data to be (str, int, etc.).
The second argument should be the name of the encrypted field (e.g. email_encrypted).
The DecryptedProperty’s name should be the same as the encrypted
DecryptedProperty
, but without the _encrypted suffix (e.g. email).