python - 对用户输入的字节串进行异或运算并反转输出
问题描述
我正在尝试获取此代码并让它打印回我给它的内容。
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。
解决方案
如果您限制 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, "你好!"
推荐阅读
- tensorflow - TensorFlow 更快的 RCNN 对象检测 api 的 Google colab 内存允许错误
- python - 无法在 Python 的字典中添加变量作为值
- arrays - 对象数组上的 Mongo db 索引
- paypal - 如何验证 PayPal webhook JSON 消息?
- php - mariabd 中长文本中的 JSON 返回“无法将数据库值转换为 Doctrine 类型 json”
- matlab - 如何从 Matlab 表格中的列中读取单位?
- javascript - 以 85 为基础的数字基础对话
- mapbox-gl-js - 复制旋转控制功能
- linux - 【Linux二进制SUID和cap_setuid的区别】
- java - 定位器不起作用,除了 WebView 中 Appium for Android 上的 id