使用M2Cryp的Python/SqlAlchemy计算列

2024-06-02 08:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的postgres数据库中有两个外部表,它们是“相关的”,没有通过“外键”正式连接(出于安全原因),称为Account和Profile。你知道吗

Account有一个名为'encrypted_UUID'的列,Profile有一个名为'UUID'的列,其中Account中的一行可以通过解密帐户的UUID并用解密的UUID搜索Profile中的行来非正式地与Profile中的一行相关联。你知道吗

我已经成功地使用M2Crypto从帐户解密了各个uuid:

import hashlib
import M2Crypto.EVP

ENCRYPT = 1
DECRYPT = 0

def hash_key(key_phrase=None):
    hasher512 = hashlib.sha512()
    if key_phrase is None:  # get from vault
        key_phrase = vault_key
    hasher512.update(str(key_phrase))
    return hasher512.digest()

def crypt(data, key_phrase=None, iv=None, whichway=DECRYPT):
    key = hash_key(key_phrase)
    if iv is None:
        iv = vault_iv
    cipher = M2Crypto.EVP.Cipher(algo, key, iv, whichway)
    return cipher.update(data) + cipher.final()

def decrypt(data, key_phrase=None, iv=None):
    return crypt(data, key_phrase, iv, DECRYPT)

def encrypt(data, key_phrase=None, iv=None):
    #data = data.encode('utf-8')
    return crypt(data, key_phrase, iv, ENCRYPT)

其中vault_keyvault_ivalgo是我将保密但用于加密/解密的内容。你知道吗

因此,对于任何帐户,我都可以说decrypt(Account.query.all()[0].uuid)并获取解密的UUID字符串,然后使用该解密的UUID查找相应的概要文件。你知道吗

现在,我尝试使用SQLAlchemy对两个表Account进行连接,并使用Account上解密的UUID的计算列对这两个表进行配置。你知道吗

以下是我为模特们准备的:

class Account(db.Model):
    encrypted_uuid = db.Column(db.LargeBinary())
    ...
    @hybrid_property
    def decrypted_uuid(self):
        return decrypt(self.encrypted_uuid)

    @decrypted_uuid.expression
    def decrypted_uuid(cls):
        return decrypt(cls.encrypted_uuid)

class Profile(db.Model):
    uuid = db.Column(db.String())
    ...

下面是我加入的尝试:

query = db.session
            .query(Account.email, Profile.last_name, Profile.first_name)
            .join(Profile, Profile.uuid == Account.decrypted_uuid)

但是,我在尝试进行查询时出错:

TypeError: expected a readable buffer object

其中堆栈可以追溯到在Account模型中对cls.encrypted_uuid调用decrypt。你知道吗

根据我过去的经验,计算列是通过几乎完全模仿hybrid\u属性/方法定义下的计算得到的。你知道吗

我觉得这是因为我试图调用decrypt类的东西,而不是decrypt函数所期望的str类。你知道吗


Tags: keynonedbdatareturnuuiddefaccount