首页 > 解决方案 > python-从变量中读取一定数量的字节

问题描述

我正在尝试实现 AES 算法,该算法将消息划分为每个 1 字节的 b 块(AES-128 每个状态单元需要 1 个字节)。所以,如果消息是:“这是星期六,是时候讲故事了。”,我必须从中读取 1 个字节并将其存储在状态单元中。

所以,我的第一个问题是,是否可以从变量中读取(或提取)一定数量的字节?

紧接着的问题是,“如果可以从一个变量中获取一定数量的字节,那么,我们如何获取该字节中的位?

标签: pythoncryptography

解决方案


最近不得不这样做。这是一个选项:

从 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(这是一个ints 数组)并选择您想要的位;例如(block_bytes[4] >> 7) & 1

也许这个答案也有帮助。


推荐阅读