我的代码中出现TypeError:^:'bytes'和'bytes'

时间:2019-07-11 19:42:34

标签: python cryptography byte typeerror

我是python3的新手,尝试在下面打印first_block值时遇到以下错误。

 File "cbcmodechal10.py", line 18, in main
    first_block = iv ^ plaintext[0]
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'

也可以请人解释为什么会发生这种情况,尽管两个变量都以字节为单位,但是为什么此操作不成功?

我知道utf-8编码存在一些问题,但不知道是什么?

#!/bin/bash/python3
import urllib.request
import base64
from Crypto.Cipher import AES

def main():
    file = urllib.request.urlopen('https://cryptopals.com/static/challenge-data/10.txt')
    ciphertext = file.read().decode('utf-8')
    cipher = base64.b64decode(ciphertext)
    key = bytes('YELLOW SUBMARINE', 'utf-8')
    iv  = bytes('\x00' * 16, 'utf-8')
    blocksize = 16
    chunks = [cipher[i:i+blocksize] for i in range(0, len(cipher), blocksize)]
    #print(chunks[0])
    cipher1 = AES.new(key, AES.MODE_ECB)
    blocks = int(len(cipher) / blocksize)
    plaintext = [cipher1.decrypt(chunks[j]) for j in range(0, blocks)]
    first_block = iv ^ plaintext[0]
    print(first_block)

if __name__ == '__main__':
    main()

预期的输出:b“我回来了,我是”

1 个答案:

答案 0 :(得分:0)

正如我所说,您必须使用单个字节完成

first_block = bytes([x^y for x, y in zip(iv, plaintext[0])])

这给了我

b"I'm back and I'm"

编辑:,因为@chepner建议这样做也可以:

first_block = bytes(map(operator.xor, iv, plaintext[0]))