<p>如果您只想执行异或,那么如果使用<code>bytearray</code>,则不需要<code>chr()</code>和<code>ord()</code>。</p>
<p>事实上,你的功能就变成了一条直线</p>
<pre><code>def xor_c(a):
return bytearray([b^0xA8 for b in bytearray(a)])
</code></pre>
<p>而且效果很好</p>
<pre><code>In [4]: xor_c('Test')
Out[4]: bytearray(b'\xfc\xcd\xdb\xdc')
In [5]: r1 = xor_c('Test')
In [6]: r2 = xor_c(r1)
In [7]: r2
Out[7]: bytearray(b'Test')
</code></pre>
<p>你的例子有问题。这是输入:
<img src="https://i.stack.imgur.com/9KuSf.png" alt="input image"/></p>
<p>这是双异或后的输出:
<img src="https://i.stack.imgur.com/19qfA.png" alt="output"/></p>
<p>注意,在某些地方“'”被转换成<code>i</code><em>或</em>a<code>j</code>。这是<em>不</em>可能与一个普通的双异或。</p>
<p>你确定你使用了我上面提供的代码吗?因为如果我在二进制文件上运行它,两次异或数据等于原始数据:</p>
<pre><code>In [1]: def xor_c(a, c=0xA8):
...: return bytearray([b^c for b in bytearray(a)])
...:
In [2]: with open('foo.gz', 'rb') as inf:
data = inf.read()
...:
In [3]: data2 = xor_c(xor_c(data))
In [4]: cmp(data, data2)
Out[4]: 0
</code></pre>
<p>当我将数据写入磁盘并进行比较时,文件也是相同的:</p>
<pre><code>In [5]: with open('foo2.gz', 'wb') as outf:
outf.write(data2)
...:
> ll foo*
-rw-r--r-- 1 rsmith rsmith - 4049792 Apr 16 13:15 foo2.gz
-rw-r--r-- 1 rsmith rsmith - 4049792 Apr 16 12:39 foo.gz
> diff foo*
</code></pre>