在我目前正在进行的这个Cryptopals Challenge中。我有正确的汉明函数和可行(尽管可能不正确)FindKey和XOR函数。
到目前为止,我有这段代码......
import base64
def binary(n):
return '{0:08b}'.format(n)
def Hamm(s1, s2):
d = 0
for c1, c2 in zip(s1, s2):
if c1 != c2:
b1 = binary(c1)
b2 = binary(c2)
for a, b in zip(b1, b2):
if a != b:
d += 1
return(d)
def FindKey(b64_s):
key_dict = {}
low = 9999
previous = 0
for size in range(2, 40):
ham1 = b64_s[previous : size + 1]
ham2 = b64_s[size + 1 : size * 2 + 1]
low = Hamm(ham1, ham2)/size
key_dict = {low : size}
previous = size
return(key_dict[low])
def XOR(byte_string):
result = ''
key = max(byte_string, key=byte_string.count) ^ ord('e')\
for b in byte_string:
result += chr(b ^ key)
print(result)
# get base64 file
b64_string = ''
with open("TestFile_Challenge06_CSIS463.txt") as f:
for line in f:
b64_string = b64_string + str(line)
XOR(base64.b64decode(b64_string))
答案 0 :(得分:2)
再次阅读你写的内容:
是两个字符串之间的不同位数
您在代码中所做的是获取两个字符串之间不同的字符的总数,而不是位。
我修改了你的代码以修复它:
def Hamm(s1, s2):
d = 0
for ch1, ch2 in zip(s1, s2):
c1 = ord(ch1)
c2 = ord(ch2)
while c1 or c2:
b1 = c1 & 1
b2 = c2 & 1
d += b1 ^ b2
c1 >>= 1
c2 >>= 1
return d