我已经研究了stackoverflow上的类似错误,但没有任何帮助我已经实现了采用编码的十六进制数据输入(16进制,即IDEA纯文本大小的64位)的IDEA算法。例如,使用utf-8编码/解码:
KEY = int('006400c8012c019001f4025802bc0320', 16)
plain_text = 'HiStackO'
cryptor = IDEA(KEY) # Initialize cryptor with 128bit key
cipher_text = cryptor.encrypt(plain_text)
deciphered_text = cryptor.decrypt(cipher_text)
下面的Encyrpt /解密功能输出:
Original text = HiStackO
Hex encoded text = 4869537461636b4f
Ciphered text = b6315c103ab29de1
Deciphered text = HiStackO
[我遇到一些文本字符串的问题,例如'thinghwr'成功解密/加密,但对于'thingher'我得到
UnicodeDecodeError:'utf-8'编解码器无法解码位置的字节0xcd 1:无效的继续字节
我尝试过latin-1和其他编码器,但结果不是原始的。至于字节,我试图通过一次读取8个字节来加密MP3歌曲文件,对新的加密文件进行解码,加密和写入加密]
cryptor = IDEA(KEY) # Initialize cryptor with 128bit key
in_file = open("song.mp3", "rb")
out_file = open("encrypted.mp3", "w")
bytes8 = in_file.read(8)
while bytes8:
res = cryptor.encrypt(bytes8.decode("latin-1"), codec="latin-1")
print(res)
res = ''.join('0' * (16 - len(res))) + res
out_file.write(res)
bytes8 = in_file.read(8)
in_file.close()
out_file.close()
每个'res'是16个十六进制数字,其中包含加密/解密的文本并写入文件。该文件已成功加密,没有任何问题。
至于解密,我正在使用以下方法:
in_file = open("encrypted.mp3", "r")
out_file = open("decrypted.mp3", "wb")
bytes8 = in_file.read(16)
while bytes8:
res = cryptor.decrypt(bytes8)
print(res)
out_file.write(res.encode())
bytes8 = in_file.read(16)
in_file.close()
out_file.close()
在几次成功解密后的解密过程中,出现以下错误:
line 136, in decrypt
return bytes.fromhex(res).decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte
第136行是解密功能:
res = self.calculate_cipher(self.dec_sub_keys, cipher_text)
res = ''.join('0' * (16 - len(res))) + res
return bytes.fromhex(res).decode()
我尝试了不同的编码,但是没有任何效果我在这里做错了什么?我是Python的新手,以前曾处理过编解码器。加密/解密功能:
def encrypt(self, plain_text='', is_hex=False, codec='utf-8'):
if not is_hex:
plain_text = plain_text.encode(codec).hex()
plain_text = get_bin_block(plain_text)
return self.calculate_cipher(self.enc_sub_keys, plain_text)
def decrypt(self, cipher_text='', codec='utf-8'):
cipher_text = get_bin_block(cipher_text)
res = self.calculate_cipher(self.dec_sub_keys, cipher_text)
res = ''.join('0' * (16 - len(res))) + res
return bytes.fromhex(res).decode(codec)
get_bin_block列表是将文本转换为4个16位二进制块以计算加密/解密的功能
res = self.calculate_cipher(self.dec_sub_keys, cipher_text)
res = ''.join('0' * (16 - len(res))) + res
return bytes.fromhex(res).decode()
calculate_cipher
时,根据cipher_text
,可能会以任意十六进制数字结尾。[然后您尝试
.decode()
相应的bytes
时,Python默认尝试使用UTF-8编码。这种编码无法解释所有可能的字节序列为文本;一些值和顺序是非法的。您说您“尝试了不同的编码”;但您必须选择一个真正可以实现此目的的程序,并确保在整个程序中始终使用它。
问题不在于您正在读取二进制文件。问题是,您正在尝试将加密的数据存储为二进制数据,尽管这是一个非常复杂的系统,需要找出十六进制数字(作为文本),找到与这些数字相对应的字节,然后将这些字节解码回字符串以从中返回模块,然后再次对其进行编码以写入文件。如果要生成字节,则应直接生成字节。另外,没有什么可以说您不能编写一个表示二进制文件中加密结果的文本文件,反之亦然-只要您可以证明该过程是可逆的即可。在此具有适当的understanding of the fundamentals非常重要。您
无法
希望跳过步骤,只是为当前问题找到解决方案,然后继续生活-您将在下一个机会中再次绊倒。