【问题标题】:python- reading certain number of bytes from a variablepython-从变量中读取一定数量的字节
【发布时间】:2019-04-29 06:45:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: python cryptography


    【解决方案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(这是ints 的数组)获取所需的字节并选择您想要的位;例如(block_bytes[4] >> 7) & 1.

    也许this answer 也有帮助。

    【讨论】:

    • 非常感谢,不过,将消息转化为比特(就像我在这里实现的方式一样),这样实现 AES 好吗?
    • 大多数 AES 操作都是面向字节的......正如我所说:block_bytes[3](例如)是一个字节(表示为int)。这应该很好用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多