【发布时间】:2020-07-30 22:25:09
【问题描述】:
假设用于加密文件的密钥是这个。
SDEREvalYDHK3xcuzChG7CU4hLBaoaVSvaJg_Fqo7UY=
加密工作正常。但是,当我使用 hmac.compare_digest() 时,未检测到正在使用的密钥的细微变化。
SDEREvalYDHK3xcuzChG7CU4hLBaoaVSvaJg_Fqo7UZ=
请注意,倒数第二个字符从Y 更改为Z。解密仍然有效,但我预计它会失败。
我可能做错了什么?如果有任何帮助,我正在使用 PyCryptodome 模块。
import os, hmac, hashlib
from base64 import urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
BS = AES.block_size
class CRYPTOPRACTICE:
def key(self):
with open("k.txt", "rb") as k:
return urlsafe_b64decode(k.read())
def e(self, file):
with open(file, "rb") as data:
IV = os.urandom(BS)
e = AES.new(self.key(), AES.MODE_CBC, IV).encrypt(pad(data.read(), BS))
sig = hmac.new(self.key(), e, hashlib.sha256).digest()
with open(file + ".encrypted", "wb") as enc:
enc.write(IV + e + sig)
os.remove(file)
def d(self, file):
with open(file, "rb") as data:
IV = data.read(BS)
e = data.read()[:-32]
data.seek(-32, os.SEEK_END)
sig = data.read()
auth = hmac.new(self.key(), e, hashlib.sha256).digest()
if hmac.compare_digest(sig, auth):
d = unpad(AES.new(self.key(), AES.MODE_CBC, IV).decrypt(e), BS)
with open(file[:-10], "wb") as dec:
dec.write(d)
data.close()
os.remove(file)
else: print(f"Fail: {file}")
a = CRYPTOPRACTICE()
a.e("test.txt")
a.d("test.txt.encrypted")
【问题讨论】:
-
我正在使用 PyCryptodome 模块。我也更新了这个问题,所以这也会反映出来。
标签: python encryption aes hmac cbc-mode