python - python-从变量中读取一定数量的字节
问题描述
我正在尝试实现 AES 算法,该算法将消息划分为每个 1 字节的 b 块(AES-128 每个状态单元需要 1 个字节)。所以,如果消息是:“这是星期六,是时候讲故事了。”,我必须从中读取 1 个字节并将其存储在状态单元中。
所以,我的第一个问题是,是否可以从变量中读取(或提取)一定数量的字节?
紧接着的问题是,“如果可以从一个变量中获取一定数量的字节,那么,我们如何获取该字节中的位? ”
解决方案
最近不得不这样做。这是一个选项:
从 itertools 导入 islice
byteorder = 'big'
plain = b"This is saturday, and it is time to tell tale."
def chunked(iterable, n):
it = iter(iterable)
values = bytes(islice(it, n))
while values:
yield values
values = bytes(islice(it, n))
for block_bytes in chunked(plain, n=8):
block_int = int.from_bytes(block_bytes, byteorder)
print(block_bytes, bin(block_int))
哪个输出
b'This is ' 0b101010001101000011010010111001100100000011010010111001100100000
b'saturday' 0b111001101100001011101000111010101110010011001000110000101111001
b', and it' 0b10110000100000011000010110111001100100001000000110100101110100
b' is time' 0b10000001101001011100110010000001110100011010010110110101100101
b' to tell' 0b10000001110100011011110010000001110100011001010110110001101100
b' tale.' 0b1000000111010001100001011011000110010100101110
请注意,byteorder
也可以'little'
。
从中block_int
很容易获得各个位:例如,最低有效位是block_int & 1
; 对于其他位置的位,您可以移动:(block_int >> 5) & 1
等等,或者您从中获取所需的字节block_bytes
(这是一个int
s 数组)并选择您想要的位;例如(block_bytes[4] >> 7) & 1
。
也许这个答案也有帮助。
推荐阅读
- php - 为特定类别生成 URL
- directx - DirectCompute 着色器:如何摆脱警告 X3205: 'round'
- excel - VBA - 将文件另存为 PDF 到具有预定义名称的特定位置
- spring-boot - Spring集成HttpRequestExecutingMessageHandler ContentType问题
- python-3.x - 返回 Null 类型数据的 Python 函数
- spring - Spring将不同的属性文件绑定到不同的bean
- swift - Reality Composer 默认锚点
- python - 在按下按钮之前,如何在另一个线程中运行函数,然后如何在没有 JavaScript 的情况下更新该线程中的网页?
- c# - PDFSharpCore XImage.FromStream
- visual-studio - 在 Visual Studio 中禁用连字