【发布时间】:2021-02-28 05:03:42
【问题描述】:
我正在使用它来加密文件,然后使用 AES-GCM 解密文件:
(如果尚未安装,请先执行pip install pycryptodome)
import Crypto.Random, Crypto.Protocol.KDF, Crypto.Cipher.AES
def cipherAES_GCM(pwd, nonce):
key = Crypto.Protocol.KDF.PBKDF2(pwd, nonce, count=100_000)
return Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_GCM, nonce=nonce)
# encrypt
plaintext = b'HelloHelloHelloHelloHelloHelloHello' # in reality, read from a file
key = b'mykey'
nonce = Crypto.Random.new().read(16)
c, tag = cipherAES_GCM(key, nonce).encrypt_and_digest(plaintext)
ciphertext = nonce + tag + c # write ciphertext to disk as the "encrypted file"
# decrypt
nonce, tag, c = ciphertext[:16], ciphertext[16:32], ciphertext[32:] # read from the "encrypted file" on disk
plain = cipherAES_GCM(key, nonce).decrypt_and_verify(c, tag).decode()
print(plain) # HelloHelloHelloHelloHelloHelloHello
这是否被认为是一种好的加密做法,这种文件加密实施的潜在弱点是什么?
备注:我有 10,000 个文件要加密。如果每次加密文件时,我都会调用 KDF(count 值很高),这将非常低效!
更好的解决方案是:只调用一次 KDF(使用 nonce1),然后对每个文件执行:
nonce2 = Crypto.Random.new().read(16)
cipher, tag = AES.new(key, AES.MODE_GCM, nonce=nonce2).encrypt_and_digest(plain)
但这是否意味着我必须为每个文件将nonce1 | nonce2 | ciphertext | tag 写入磁盘?这会为每个文件添加一个额外的 16 字节 nonce1...
【问题讨论】:
标签: python encryption cryptography aes aes-gcm