Reputation: 67
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))
Upvotes: 2
Views: 3145
Reputation: 43166
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'))
Upvotes: 3