微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决破解由 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 举报,一经查实,本站将立刻删除。