Last active
March 4, 2023 05:11
-
-
Save darkmatter18/fa70c6fc7c1e9a8b4cdef8e970533b98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import hashlib | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
from mongoengine import fields | |
class EncryptField(fields.BaseField): | |
def __init__(self, key: str, **kwargs): | |
self.bs = AES.block_size | |
self.key = hashlib.sha256(key.encode()).digest() | |
super().__init__(**kwargs) | |
def to_python(self, value): | |
if isinstance(value, str) or not isinstance(value, bytes): | |
return value | |
else: | |
return self.decrypt(value) | |
def to_mongo(self, value): | |
return self.encrypt(value) | |
def validate(self, value): | |
if not isinstance(value, str): | |
self.error("StringField only accepts string values") | |
def encrypt(self, raw): | |
raw = self._pad(raw) | |
iv = Random.new().read(AES.block_size) | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return base64.b64encode(iv + cipher.encrypt(raw.encode())) | |
def decrypt(self, enc): | |
enc = base64.b64decode(enc) | |
iv = enc[:AES.block_size] | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') | |
def _pad(self, s): | |
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) | |
def _unpad(self, s): | |
return s[:-ord(s[-1:])] | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pycryptodome | |
mongoengine |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mongoengine import connect, Document | |
from encrypted_field import EncryptField | |
connect(host="mongodb://<user>:<passwd>@<ip>:27017/<db>", uuidRepresentation='standard') | |
class TestEnc(Document): | |
data = EncryptField(key="Pc0OOWSdhP8wXpTqhDslnrK7HTW4uF0oBN4m9kbELg0=") | |
TestEnc(data="abc").save() | |
for x in TestEnc.objects.all(): | |
print(x.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment