简体   繁体   English

如何在 SQLAlchemy 中对加密列使用求和函数?

[英]How to using sum function with encrypted column in SQLAlchemy?

I have used EncryptedType from sqlalchemy_utils to encrypt data of the specific column which will make when inserting data into the table or selecting data, the data of encrypted column will be encrypted.我使用了sqlalchemy_utils中的EncryptedType来加密特定列的数据,这将使在将数据插入表或选择数据时,加密列的数据将被加密。

This is the ORM structure of my database which have encrypted in value column.这是我的数据库的 ORM 结构,它在value列中进行了加密。

from sqlalchemy_utils import EncryptedType
from sqlalchemy_utils.types.encrypted.encrypted_type import AesEngine

class Products(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(400))
    value = db.Column(EncryptedType(db.Integer, secret_key, AesEngine,'pkcs5')) 

And this is the result when select data in psql which you will unable to see the data of value column because it encrypted.这是在 psql 中选择数据时的结果,您将无法看到value列的数据,因为它已加密。

 id |  name   |                       value                        
----+---------+----------------------------------------------------
  1 | Macbook | \x6977764a59556346536e6b674d7a6439312f714c70413d3d
  2 | IPhone  | \x6a6b51757a48554739666756566863324662323962413d3d
  3 | IPad    | \x416d54504b787873462f724d347144617034523639673d3d

But when i select data by using ORM, it will decrypt the data automatically.但是当我使用 ORM 选择数据时,它会自动解密数据。

And this is my code.这是我的代码。

product_query = Products.query.order_by(Products.id.asc()).all()
for product in product_query:
    print(product.id, ' ', product.name, ' ', product.value)

Result结果

1   Macbook   222222
2   IPhone   40000
3   IPad   60000

Problem问题
When i try to select SUM with this code当我尝试使用此代码选择 SUM 时

db.session.query(func.sum(Products.value)).all()

it got the error like this.它得到了这样的错误。

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) function sum(bytea) does not exist
LINE 1: SELECT sum(products.value) AS sum_1 

Then as i understand the error, the problem is because the data that i try to SUM it still in byte or encrypted format, so are there any way that i can sum the value of encrypted column?然后据我了解错误,问题是因为我尝试对它求和的数据仍然是字节或加密格式,所以有什么方法可以对加密列的值求和吗?

If you have the column encrypted in the database, you cannot use a database function to add the values.如果您在数据库中加密了列,则无法使用数据库函数添加值。 The database doesn't even know the values.数据库甚至不知道这些值。 You will have to transfer the data to the client and calculate the sum there.您必须将数据传输到客户端并在那里计算总和。 Yes, this is slow and inefficient, but that is the price of security.是的,这是缓慢且低效的,但这是安全的代价。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM