【发布时间】:2019-08-06 02:51:42
【问题描述】:
所以我有一个程序,它将使用 AES 加密字符串并生成以字节 [] 为单位的密码。 我希望将此密码存储在 mysql 数据库中。 我发现我们可以在 mysql 中使用 VARBINARY 数据类型来做到这一点。
我们可以通过哪些方式实现这一目标。
这是我的尝试:
import ast
import mysql.connector
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt(key, msg):
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CFB, iv)
ciphertext = cipher.encrypt(msg) # Use the right method here
db = iv + ciphertext
print(db)
cursor.executemany(sql_para_query,db)
print(cursor.fetchone())
connection.commit()
return iv + ciphertext
def decrypt(key, ciphertext):
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = cipher.decrypt(ciphertext)
return msg.decode("utf-8")
if __name__ == "__main__":
connection = mysql.connector.connect(host = "localhost", database = "test_db", user = "sann", password = "userpass",use_pure=True)
cursor = connection.cursor(prepared = True)
sql_para_query = """insert into test1 values(UNHEX(%s)) """
ed = input("(e)ncrypt or (d)ecrypt: ")
key = str(1234567899876543)
if ed == "e":
msg = input("message: ")
s= encrypt(key, msg)
print("Encrypted message: ", s)
file = open("e_tmp","wb+")
file.write(s)
print(type(s))
elif ed == "d":
#smsg = input("encrypted message: ")
#file = open("e_tmp","rb")
#smsg = file.read()
#print(type(smsg))
sql_para_query = """select * from test1"""
cursor.execute(sql_para_query)
row = cursor.fetchone()
print(row)
#smsg = str(smsg)
#msg = ast.literal_eval(smsg)
#print(msg)
#print(type(msg))
#s=decrypt(key, msg)
#print("Decrypted message: ", s)
#print(type(s))
我得到的错误:
Traceback(最近一次调用最后一次):文件 "/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py", 第 1233 行,在 executemany 中 self.execute(操作,参数)文件“/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py”, 第 1207 行,执行中 elif len(self._prepared['parameters']) != len(params): TypeError: object of type 'int' has no len()
在处理上述异常的过程中,又发生了一个异常:
Traceback(最近一次调用最后一次):文件“tmp1.py”,第 36 行,在 s= encrypt(key, msg) 文件“tmp1.py”,第 14 行,在 encrypt cursor.executemany(sql_para_query,db) 文件 "/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py", 第 1239 行,在 executemany 中 "执行操作失败;{error}".format(error=err)) mysql.connector.errors.InterfaceError: 执行操作失败; 'int' 类型的对象没有 len()
也欢迎任何其他选择。
我的最终目标是将加密文本存储在数据库中。
【问题讨论】:
标签: mysql python-3.x cryptography