首页 > 解决方案 > 对用户输入的字节串进行异或运算并反转输出

问题描述

我正在尝试获取此代码并让它打印回我给它的内容。

def xorwithmykey(str,key):
    kp = 0
    newbuf = []

    for i in range(len(str)):
        newchar = ord(str[i]) ^ ord(key[kp])
        newbuf.append(chr(newchar))

        kp = kp + 1
        if kp >= len(key):
            kp = 0

    return ''.join(newbuf).encode('hex')

我可以通过调用异或键

encoded = xorwithmykey('encodethis', 'akey')

这让我回来了

b'04050616050e11110818'

现在我想把它还给同一个函数来解码。

decoded = xorwithmykey(codecs.decode(encoded, 'hex'), codecs.decode('akey', 'hex')

这将返回一个错误:

binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

我在这里找到了这个例子:https ://snippets.bentasker.co.uk/page-1708032328-XOR-string-against-a-given-key-Python.html

但它在 Python 2 中,我正在尝试转换为 Python 3。

标签: pythonpython-3.x

解决方案


如果您限制 XOR 函数在 Python 3 中单独使用字节,您可以编码/解码任何 Unicode 字符串:

from binascii import hexlify

# Shorter version
# def xorwithmykey(s,key):
#     return bytes([c ^ key[i%len(key)] for i,c in enumerate(s)])

def xorwithmykey(s,key):
    kp = 0
    newbuf = []

    for i in range(len(s)):
        newchar = s[i] ^ key[kp]
        newbuf.append(newchar)

        kp = kp + 1
        if kp >= len(key):
            kp = 0

    return bytes(newbuf)

encoded = xorwithmykey('She said, "你好!"'.encode(), b'akey')
print(hexlify(encoded))

decoded = xorwithmykey(encoded, b'akey')
print(decoded.decode())

输出:

b'32030059120a0c1d4d4b479ddccb80dcdc84d9f843'
She said, "你好!"

推荐阅读