python - 在 python 中对二进制文件进行异或

标签 python hash xor

我正在编写一个简单的哈希函数,它获取输入并创建一个 32 位哈希文件。我陷入了异或部分。我不确定应该如何编写异或函数。请在这件事上给予我帮助。这是我已经完成的代码:

import BitVector
import io
import math
import struct

if __name__ == "__main__":
    message = raw_input("your message:")
    f= open('file.dat','w')
    f.write(message)
    f.close()

    f = open('file.dat')
    while 1:
       r = f.readline(1)
       hx = r.encode("hex")
       data = bin(int(hx, 16))[2:]
       key = 11111111
       x = int(data) ^ int(key)
       print hex(x)
       if not r:break
    f.close()

最佳答案

运算符 ^ 对您来说已经足够了。

>>> 2 ^ 1
3
>>> 3 ^ 1
2

您应该关心的是 key 的位大小和“异或”数据的位大小,以确保功能。

顺便说一句,异或运算应该只适用于整数。

import struct

key = 0xFEEEFEEE
with open('file', 'rb') as f:
    integer = f.read(4) # In fact, you could read all in.
    while len(integer) >= 4:
        # if integer is not a string longer than 4, next line crash.
        s, = struct.unpack('i', integer) # The return value is a tuple with integers.
        print key ^ s
        integer = f.read(4)

关于python - 在 python 中对二进制文件进行异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9372111/

相关文章:

c# - 为什么 "int"和 "sbyte"GetHashCode 函数生成不同的值?

java - hashmap 在 while 循环之外是不同的

c - 两个二进制数异或的问题

java - 我可以在 python 中访问 C++ 或 Java 函数吗

python - 在树莓派上使用 Opencv 显示视频流时出错

python - 将 matplotlib 偏移表示法从科学更改为简单

python - 防止 nose 发现名为 "setup"的包?

python - urlsafe_b64encode 总是以 '=' 结尾? :

c++ - 为什么 C/C++ 中没有 ^^ 运算符?

C++ XOR key 太长?