简体   繁体   中英

Increment a bytearray in Python 3?

In python 3, how would one increment a 16 byte array like so? 0x00000000000000000000000000000000 -> 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))

If you need to increment a byte string, it's easier to convert it to a number instead. Integers have a handy to_bytes method that you can use to convert x to a byte string:

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

Using this method, your code would look like this:

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM