破解由 XOR 加密的文本的密钥

问题描述

我尝试用 Python 编写我自己的 XOR 破解程序。我只是尝试了一个非常简单的例子:

THE MONEY IS BENEATH THE FLOOR BOARDS
ENIGMAENIGMAENIGMAENIGMAENIGMAENIGMAE

但它总是返回空的 (b'\x00\x00\x00\x00\x00\x...)

我认为在获取密钥和解密文本时我做错了什么。事实上,我得到了一把不是我期望的钥匙。然而,我试图找到距离最小的钥匙:

def get_key(chunks,key_length):
    # looping through ASCII characters and XORing them with each of these bytes
    best_results = [[None,10e4] for _ in range(key_length)]
    for x in string.printable:
        for i in range(len(chunks)):
            result = 0
            for j in range(len(chunks[i])):
                result += (ord(x) ^ ord(chunks[i][j]))
            if best_results[i][1] > result:
                best_results[i][0] = x
                best_results[i][1] = result

这是完整的代码

import string

def to_hex(s):
    return hex(int(s,base=16))


# Press the green button in the gutter to run the script.
def create_chunks(encrypted,key_length):
    chunks = [[] for _ in range(key_length)]
    for i in range(len(encrypted)):
        chunks[i % key_length].append(encrypted[i])
    return chunks


def get_key(chunks,10e4] for _ in range(key_length)]
    for x in string.printable:
        for i in range(len(chunks)):
            result = 0
            for j in range(len(chunks[i])):
                result += (ord(x) ^ ord(chunks[i][j]))
            if best_results[i][1] > result:
                best_results[i][0] = x
                best_results[i][1] = result
    return (best_results)


def decrypt_text(encrypted,key):
    decrypted = b''
    for i in range(len(encrypted)):
        xor = ord(encrypted[i]) ^ ord(key[i % len(key)][0])
        decrypted += bytes(xor)
    return decrypted


if __name__ == '__main__':
    # read input
    with open("output.txt","r") as f:
        encrypted = f.read()
    # THE MONEY IS BENEATH THE FLOOR BOARDS
    # ENIGMAENIGMAENIGMAENIGMAENIGMAENIGMAE
    encrypted = "11060c67000e0b0b10670412650c0c090800110669130504650805080213650c06061f0516"
    key_length = len("ENIGMA")
    # we need to create chunk of length key_length
    chunks = create_chunks(encrypted,key_length)
    key = get_key(chunks,key_length)
    print(key)
    decrypted_text = decrypt_text(encrypted,key)
    print(decrypted_text)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)