python-3.x - Python3中的XOR字节
问题描述
在尝试对 python3 中的字节进行异或运算时:
import os,binascii
import numpy as np
def xor_byte_hex_strings(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
number_of_bytes = 2
random_bytes = []
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes))
random_bytes.append(random_bytes_str)
print(random_bytes_str)
print(bytearray(random_bytes_str))
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes))
random_bytes.append(random_bytes_str)
resultant = xor_byte_hex_strings(random_bytes[0], random_bytes[1])
print("resultant = ", bytearray(resultant))
print(random_bytes)
resultant = xor_byte_hex_strings(random_bytes[1], resultant)
print(resultant)
结果是 b'\x03\x03\x0cU' 而不是 b'13ce。我们如何将格式从 b'\x03\x03\x0cU' 转换为 b'13ce?
解决方案
为什么不使用字符串和int
s 让您的生活更轻松?
import os,binascii
def xor_strings(a, b):
result = int(a, 16) ^ int(b, 16) # convert to integers and xor them together
return '{:x}'.format(result) # convert back to hexadecimal
number_of_bytes = 2
random_bytes = []
# decode() to turn it into a str.
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes)).decode()
random_bytes.append(random_bytes_str)
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes)).decode()
random_bytes.append(random_bytes_str)
print(random_bytes)
xored = xor_strings(*random_bytes)
print("resultant = ", xored.encode())
print([random_bytes[1], xored])
resultant = xor_strings(random_bytes[1], xored)
print(resultant.encode()) # encode() will turn it back to bytes if you want bytes
输出:
['4588', '3af9']
resultant = b'7f71'
['3af9', '7f71']
b'4588'
推荐阅读
- shell - if (( ... )) 的 POSIX 兼容替代方案是什么?
- mongodb - 我如何在 kubernetes 中使用 mongoconnector
- typescript - 函数返回类型取决于是否传递了可选参数
- python-3.x - 在不加载内存的情况下读取 Shapefile 的 Zip 时出现问题
- scala - 将通用附加函数迁移到 Scala 2.13 集合
- java - 如何使用嵌套的 if 语句而不是 System.exit(0); 阻止程序在蓝图类中运行?
- python - 从数据框中检索许多聚合计数的最佳方法?
- assembly - nasm 指令和宏的缩进
- solr - Solr 空间字段上的过滤器查询返回所有具有非空值的文档
- java - 如何将我的数据插入二维多维数组?