来自加密表的Psycopg2查询

2024-04-28 23:21:37 发布

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

我遇到了一个问题w。使用psycopg2从表中的加密列中进行选择。 使用

create table users (
    id BIGSERIAL NOT NULL PRIMARY KEY,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,
    secret_val_1 BYTEA,
    secret_val_2 BYTEA
);

我能够在其中插入加密值。
现在,我尝试使用psycopg2从表中查询值,方法是:

cur.execute("""
            SELECT PGP_SYM_DECRYPT(%s::BYTEA, 'compress-algo=1, cipher-algo=aes256')
            FROM users;
            """,
            ('secret_val_1',))

现在,这会引发一个错误:

ExternalRoutineInvocationException: Wrong key or corrupt data

有趣的是,当这样传递值时,它会起作用:

def query_users_decrypt(col):
    cur.execute("""
                SELECT PGP_SYM_DECRYPT({}::BYTEA, 'compress-algo=1, cipher- 
                algo=aes256') FROM users;
                """.format(col),
                (col,))

但是这对于sql注入攻击是不安全的,对吗?
有人知道怎么做才是正确的吗?谢谢


Tags: nameexecutesecretnotcolvalselectnull
1条回答
网友
1楼 · 发布于 2024-04-28 23:21:37

format()之所以有效,是因为当您将secret_val_1传入时,它最终看起来像:

  SELECT PGP_SYM_DECRYPT(secret_val_1::BYTEA, 'compress-algo=1, cipher-algo=aes256')
  FROM users;

你要找的只是一个简单的问题:

  select pgp_sym_decrypt(secret_val_1, 'compress-algo=1, cipher-algo=aes256')
    from users;

参数绑定用于传递查询所使用的值。secret_val_1不是值,因为它是列的名称

对以下内容使用参数绑定:

cur.execute("""select pgp_sym_decrypt(secret_val_1, 'compress-algo=1, cipher-algo=aes256' 
                 from users 
                where username = %s""", ('joeuser',))

相关问题 更多 >