字段基于Char类型
加密方法采用Fernet
from cryptography.fernet import Fernet
def encrypt(key, text):
cipher = Fernet(key)
return cipher.encrypt(text.encode()).decode()
def decrypt(key, encrypted_text):
cipher = Fernet(key)
return cipher.decrypt(encrypted_text).decode()
class SecretChar(fields.Char):
secretkey = tools.config.get('secretkey', '').encode()
_slots = {"_secretkey": secretkey}
def __init__(self, *args, **kwargs):
if not self.secretkey:
tools.config['secretkey'] = Fernet.generate_key().decode()
_logger.info('init secretkey %s', tools.config['secretkey'])
tools.config.save()
return super(SecretChar, self).__init__(*args, **kwargs)
def write(self, records, value):
records.env.remove_to_compute(self, records)
cache = records.env.cache
cache_value = value
records = cache.get_records_different_from(records, self, cache_value)
if not records:
return records
cache.update(records, self, [cache_value] * len(records))
if self.store:
towrite = records.env.all.towrite[self.model_name]
record = records[:1]
column_value = self.convert_to_column(cache_value, record)
for record in records.filtered('id'):
towrite[record.id][self.name] = column_value
return records
def convert_to_column(self, value, record, values=None, validate=True):
return encrypt(self.secretkey, value) if value else ''
def convert_to_read(self, value, record, use_name_get=True):
return decrypt(self.secretkey, value.encode()) if value else ''