【问题标题】:Increment a bytearray in Python 3?在 Python 3 中增加一个字节数组?
【发布时间】:2018-10-17 14:35:49
【问题描述】:

在 python 3 中,如何像这样增加一个 16 字节的数组? 0x000000000000000000000000000000000 -> 0x00000000000000000000000000000001

import base64
import Crypto
from Crypto.Cipher import AES

def incr(): 
    k = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x00\x00\x00'
    x = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    obj = AES.new(k,1)
    ciphertext = obj.encrypt(bytes(x))
    # while the leftmost byte of ciphertext produced by AES isn't 0x00
    while ciphertext[:-7] != b'\x00': 
        # increment x somehow 
        x += 1 # obviously doesn't work
        ciphertext = obj.encrypt(bytes(x))

【问题讨论】:

  • 你能澄清一下字节代表什么吗?也许是一个大端无符号 128 位整数?
  • @JanneKarila 是的,抱歉,它们是 128 位
  • 也许,你可以试试这个:Python : efficient bytearray incrementation,但不支持 bigint

标签: python arrays python-3.x


【解决方案1】:

如果您需要增加字节字符串,将其转换为数字会更容易。整数有一个方便的 to_bytes 方法,可用于将 x 转换为字节字符串:

>>> (1).to_bytes(16, 'big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'

使用此方法,您的代码将如下所示:

def incr(): 
    k = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x00\x00\x00'
    x = 0
    obj = AES.new(k, 1)
    ciphertext = obj.encrypt(x.to_bytes(16, 'big'))
    # while the leftmost byte of ciphertext produced by AES isn't 0x00
    while ciphertext[:-7] != b'\x00': 
        # increment x somehow 
        x += 1 # obviously works!
        ciphertext = obj.encrypt(x.to_bytes(16, 'big'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2021-06-24
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2013-04-22
    相关资源
    最近更新 更多