xoring bytes and str (AES CBC)
嗨,我真的很感谢在此方面的帮助,因为我真的迷路了,我不知道为什么它不起作用。
我有一个16字节的密钥和16字节的块
但是键类型是'str'并且块类型是'bytes',我想在它们之间进行异或运算,但是值不正确(我认为)
该代码基于此帖子
1 2 3 4 5 6 7 8 9 | def xor(data, key): if type(key) != str: key = str(key) l = len(key) buff="" for i in range(0,len(data)): buff+=chr(data[i]^ord(key[i])) return str.encode(buff) |
并在上下文中:(参考CBC)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | def CBC_decrypt(blocklist,IV,decrypter): ''' :param blocklist: a 16 byte item list(or other iteratable) :param IV: 16 byte sized iv :param decrypter: decrypter: a generic decrypter-must provide an decrypt(plaintext) method where plaintext is 16 byte size :return: a list of decrypted blocks of 16 bytes ''' decrypted_msg=[] prev = IV for x in blocklist: r = xor(decrypter.decrypt(x),prev) decrypted_msg.append(r) prev = x return decrypted_msg a = FileTo16ByteBlocks(path) #just read 16 bytes at a time and return a list cipher2= AES.new(loadKey(),AES.MODE_ECB) #init AES in ECB cause we had to implement CBC d = CBC_decrypt(a,iv[0],cipher2) |
在这里,我将其全部写入文件
1 2 3 4 5 | # create new file iterate through the deciphered data and write it to that file with open(str(fileSeq)+'.mp4','wb') as f: for i in d: f.write(i) f.write(b'') |
我已经尝试过其他与xor有关的事情(因为ECB解密是由library-pycrypto进行的),例如使用它的number.bytes来加长并对其进行异或
我已经尝试将其转换为整数,看看它如何进行,一切都变得非常糟糕
而且xor事情只是预感,我无法真正说明为什么这无法正常工作!
感谢所有帮助者
我已经设法解决了!
我确实认为问题确实出在xor函数上,显然xor结果的长度不是16,但是由于转换,它是变量(为什么会这样?)
我在这里添加代码,以防将来有人需要它
1 2 3 4 5 6 7 8 9 10 | def xor(data, key1): b=key1 if type(key1) is str: b = bytes(key1,encoding='utf8') iData = int.from_bytes(data, sys.byteorder) iKey = int.from_bytes(b, sys.byteorder) xored = iData ^ iKey xored = xored.to_bytes(len(data), sys.byteorder) return xored |