问题描述
下午好,我正在尝试编写一个程序来读取.bmp文件,并使用???和一次性垫使用给定的初始值对其进行加密。
前36个字节构成了图像的标题,未加密,只是将其复制到新文件中
从0x36到末尾的图像数据被分组为四个字节的字,并且每个字都使用encrypted进行加密。
为避免更改图像的大小,请勿在加密的图像中包含“ 0 =???”。
截至目前,这就是我所拥有的:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
from Crypto.Util import Counter
filename = "Image11.bmp"
filename_out = "Image11Encrypted.bmp"
key = 0xe0984dd3
bkey = key.to_bytes(32,'big')
cipher = AES.new(bkey,AES.MODE_CTR,initial_value= 0xff128eff)
def encrypt(filename,filename_out,key):
with open(filename,"rb") as f:
clear = f.read()
clear_trimmed = clear[64:-2]
ciphertext = clear_trimmed
ciphertext = cipher.encrypt(pad(clear_trimmed,16))
ciphertext = clear[0:64] + ciphertext + clear[-2:]
with open(filename_out,"wb") as f:
f.write(ciphertext)
encrypt(filename,key)
print("Encrypted using AES in CTR mode and saved to \"" + filename_out + "\"")
但是,我一直遇到此错误:
。
任何帮助都是很好的,不确定从这里要去哪里
解决方法
使用here描述了使用PyCryptodome进行CTR模式的配置。有两种指定计数器块的方法:通过设置随机数(参数nonce
)和起始值(参数initial_value
)。如果未指定随机数,则将隐式生成块大小一半的随机随机数。
另一种方法是定义counter block object(参数counter
),可用于详细指定计数器块的组成部分(前缀,计数器,后缀)。
如果仅要指定起始值,则必须使用参数initial_value
代替counter
:
cipher = AES.new(bkey,AES.MODE_CTR,initial_value=0xff128eff)
如上所述,这会隐式创建一个随机数为一半的随机数,可以使用cipher.nonce
来确定。
请注意:该代码缺少16字节IV的确定,这是解密所需的。 IV由随机数和计数器组成,通常放在密文之前的字节级别上。
此外,根据这个问题,前36个字节不应该加密,稍后再说数据从0x36开始( = 54),并在代码64中用作数据的开头。这似乎不一致。