基于AES的图像加解密:输入密码哈希时触发类型错误
问题解决:哈希前必须对字符串进行编码
错误原因
hashlib.sha256()函数要求传入字节类型的数据,但你从输入框获取的enc_pass是字符串类型,直接传入就会触发类型错误。
修复方法
将字符串编码为字节(常用utf-8编码),修改代码中计算哈希的那一行:
原代码:
password = hashlib.sha256(enc_pass).digest()
修改后:
password = hashlib.sha256(enc_pass.encode('utf-8')).digest()
完整修改后的代码片段
def pass_alert(): messagebox.showinfo("Password Alert","Please enter a password.") def enc_success(imagename): messagebox.showinfo("Success","Encrypted Image: " + imagename) # image encrypt button event def image_open(): global file_path_e enc_pass = passg.get() if enc_pass == "": pass_alert() else: # 对字符串进行UTF-8编码后再计算哈希 password = hashlib.sha256(enc_pass.encode('utf-8')).digest() filename = filedialog.askopenfilename() file_path_e = os.path.dirname(filename) encrypt(filename,password)
补充说明
哈希算法本质是对字节流进行运算,所以必须先把字符串转换成字节格式。使用utf-8编码能确保不同操作系统、不同语言环境下,字符串转字节的结果一致,避免出现加密解密不匹配的问题。
内容的提问来源于stack exchange,提问作者Saadi Qazi
相关产品推荐
相关产品推荐

