[英]Increment a bytearray in Python 3?
在python 3中,如何像這樣增加一個16字節數組? 0x00000000000000000000000000000000000000-> 0x00000000000000000000000000000000000001
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))
如果需要增加字節字符串,則將其轉換為數字會更容易。 整數有一個方便的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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.