You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Adunatio/internal_lib/EncryptedField.py

46 lines
1.1 KiB

4 years ago
import re
from flask import current_app
4 years ago
from mongoengine.base import BaseField
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
4 years ago
class EncryptedStringField(BaseField):
"""A unicode encrypted string field."""
keyPair = None
def __init__(self, **kwargs):
self.keyPair = RSA.importKey(open("privkey.pem").read())
4 years ago
super().__init__(**kwargs)
def __get__(self, instance, owner):
value = instance._data.get(self.name)
encryptor = PKCS1_OAEP.new(self.keyPair.publickey())
return encryptor.decrypt(value)
def __set__(self, instance, value):
4 years ago
key = self.name
encryptor = PKCS1_OAEP.new(self.keyPair.publickey())
instance._data[key] = encryptor.encrypt(value)
instance._mark_as_changed(key)
def to_python(self, value):
4 years ago
if isinstance(value, str):
return value
try:
value = value.decode("utf-8")
except Exception:
pass
return value
def lookup_member(self, member_name):
return None
def prepare_query_value(self, op, value):
return super().prepare_query_value(op, value)