[英]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.