XOR问题:“ ord需要一个字符,但找到了长度为2的字符串”

问题描述

代码从两个二进制文件读取字节,然后使用XOR进行字节比较。基本上是从密钥文件中读取一个奇数字节,然后将其移入text.bin文件中。

密钥文件中的所有字节都是必须与text.bin文件中的字节进行比较的字节。

从技术上讲,它应该比较两个bin文件中的两个读取字节,但出现错误

    output = (ord(mask)^ord(a)) # XOR
TypeError: ord() expected a character,but string of length 2 found

k = open ("key.bin","rb")
t = open ("text.bin","rb")

k.seek(0); t.seek(0); position = 0

while 1:
        offset = k.read(1)
        mask = k.read(2)
        print(str(mask))
        
        if not offset:
                break
        if not mask:
                break
        
        shift=int(ord(offset))
        print(shift)
        position = position + shift
        
        t.seek(position)
        a = t.read(1)
        
        output = (ord(mask)^ord(a))
        print (chr(output),end="")
        
k.close() ; d.close()

仅当mask = k.read(2)从第二个字节读取时才会发生。 “长度为2的字符串”可能是读取了错误的十六进制字符串而不是字节?

解决方法

由于top - 03:24:16 up 3 days,20:11,0 users,load average: 0.54,0.59,0.59 Tasks: 3 total,1 running,2 sleeping,0 stopped,0 zombie %Cpu(s): 1.6 us,3.6 sy,0.0 ni,94.8 id,0.0 wa,0.0 hi,0.0 si,0.0 st KiB Mem : 63587180 total,1169784 free,58092788 used,4324608 buff/cache KiB Swap: 33550332 total,33199676 free,350656 used. 4942932 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 6 root 20 0 5652304 998.9m 20596 S 46.8 1.6 6:41.26 tensorflow_mode 1 root 20 0 18364 1580 1304 S 0.0 0.0 0:00.06 tf_serving_entr 105 root 20 0 36600 1724 1284 R 0.0 0.0 0:00.55 top 的长度为2,而k.read(2)的长度为1,导致此错误。

尝试一下:

ord