问题描述:

I am new to psycopg2 and postgresql (and frankly coding) so I apologize if I have anything wrong to begin with.

I am hoping to create a python script that when prompted by the user for an ID number, it finds the associated encrypted number in the database and then decrypts it and sends it back.

I haven't been able to get my script to output the decrypted number and get what seems to be where it is located in the memory.

Here is my code and result.

>>> import psycopg2

>>> conn = psycopg2.connect(database="db_name", user="db_user", password="db_pswrd", host="db_IP")

>>> cur = conn.cursor()

>>> id = input("Enter an id: ")

Enter an id: 123456

>>> id= str(id)

>>> cur.execute("SELECT id, decrypt(num, 'decryption_key', 'decryption_type') from table_name where id in (%s) ", (id,))

>>> for record in cur:

print(record)

(123456, <memory at 0x02483590>)

The number entered as the id must be a string and the encrypted is type bytea if that is relevant at all.

When I use the part in the cur.execute it works just fine in PGAdmin so I am not sure where I could be going wrong.

Please let me know if there is anything else I need to include, I changed some sensitive information.

I am using python 3.4 by the way.

网友答案:

decrypt returns bytea. As you are printing the row not the individual values, it is not adapted back. Print the values in instead:

for r in cur:
    print(r[0], r[1])

Tested in Python 2.7:

query = "select decrypt(encrypt('1', 'xyz', 'aes'), 'xyz', 'aes');"
cursor.execute(query)
rs = cursor.fetchall()
for r in rs:
    print r, r[0]

Output:

(<read-only buffer for 0xb732b0e0, size 1, offset 0 at 0xb67a9ca0>,) 1
相关阅读:
Top