【发布时间】:2020-02-14 01:01:50
【问题描述】:
首先,对不起,关于这个问题有很多问题,我淹没在很多答案中,但我仍然不明白,因为我的代码只要我写入文件就可以工作(?)
那么,为什么会这样:
# encrypt and write to file
data_to_encrypt = "mytext"
data = data_to_encrypt.encode('utf-8')
ciphered_bytes = cipher_encrypt.encrypt(data)
ciphered_data = ciphered_bytes
print(ciphered_data)
with open(fileConfigBIN, "wb") as binary_file:
binary_file.write(ciphered_data)
# read the file and decrypt
with open(fileConfigBIN, "rb") as binary_file:
data1 = binary_file.read()
print(data1)
deciphered_bytes = cipher_decrypt.decrypt(data1)
decrypted_data = deciphered_bytes.decode('utf-8')
print(decrypted_data)
输出:
b'\xa0U\xee\xda\xa8R'
b'\xa0U\xee\xda\xa8R'
我的文本
但只是通过注释写入文件(文件仍然存在相同的信息):
#data_to_encrypt = "mytext"
#data = data_to_encrypt.encode('utf-8')
#ciphered_bytes = cipher_encrypt.encrypt(data)
#ciphered_data = ciphered_bytes
#print(ciphered_data)
#with open(fileConfigBIN, "wb") as binary_file:
# binary_file.write(ciphered_data)
with open(fileConfigBIN, "rb") as binary_file:
data1 = binary_file.read()
print(data1)
deciphered_bytes = cipher_decrypt.decrypt(data1)
decrypted_data = deciphered_bytes.decode('utf-8')
print(decrypted_data)
我明白了:
b'\xa0U\xee\xda\xa8R'
Tkinter 回调异常 回溯(最近一次通话最后): 调用中的文件“C:\Users.......\Python37-32\lib\tkinter__init__.py”,第 1705 行 返回 self.func(*args) AbrirConfig 中的文件“C:\Users\Fabio\source......”,第 141 行 decrypted_data = deciphered_bytes.decode('utf-8') UnicodeDecodeError:“utf-8”编解码器无法解码位置 1 的字节 0xdd:无效的继续字节
读取的代码使用的是和注释部分相同的文件保存!
我尝试保存并读取 'latin-1'、'ISO-8859-1' 等。它没有给出错误,但只返回奇怪的字符
使用 Python 3.7
提前致谢!
编辑:
完整的工作最小代码:
from Crypto.Cipher import AES
fileConfigBIN = "data.dat"
key = b'\x16\x18\xed\x1c^\xaaGN\rl\xc0]\xf0t=\xd0\xdc]t\xaf\xb2\x12,\xe6\xfc\xd6\x11-\x10\xb4\xb1\x0b'
cipher_encrypt = AES.new(key, AES.MODE_CFB)
iv = cipher_encrypt.iv
cipher_decrypt = AES.new(key, AES.MODE_CFB, iv=iv)
def Encrypt():
data_to_encrypt = "MyTextToEncrypt"
data = data_to_encrypt.encode('utf-8')
ciphered_bytes = cipher_encrypt.encrypt(data)
ciphered_data = ciphered_bytes
with open(fileConfigBIN, "wb") as binary_file:
binary_file.write(ciphered_data)
print("CRYPTED DATA SAVED TO FILE: ", str(ciphered_data))
def Decrypt():
with open(fileConfigBIN, "rb") as binary_file:
data1 = binary_file.read()
print("DATA READ FROM FILE: ", data1)
deciphered_bytes = cipher_decrypt.decrypt(data1)
decrypted_data = deciphered_bytes.decode('utf-8')
print("DECRYPTED DATA: ", decrypted_data)
Encrypt() #comment this function to show the problem
print('---------------------')
Decrypt()
伙计们,我做到了!感谢@Hoenie 洞察力,对于每次加密,我都会存储 iv 值并在需要时使用它来解密。如果碰巧需要再次加密,它会保存另一个iv值等等......谢谢谢谢!
【问题讨论】:
-
只有您知道
cipher_decrypt和cipher_encrypt是什么,以及它们是如何初始化的。如果您没有显示完整的工作示例,那么我们将无法运行它并找出问题所在。我只能说解密失败并返回垃圾数据。 -
我们需要一个minimal reproducible example。
-
你试过编码
cp1252吗? -
cp1252 当我解密时返回像.. †“m]Û&{r¿ÉÞY%Œè 。我在这里错过了什么?
标签: python encryption utf-8 binaryfiles