1 回答

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是一個(gè)確實(shí)有效的示例,但請(qǐng)不要將其用于任何敏感的事情,因?yàn)樗话踩?/p>
正確使用密碼學(xué)原語(yǔ)是困難的;相反,您應(yīng)該使用比您和我更聰明的人編寫的更高級(jí)別的食譜,并證明在正確使用時(shí)是安全的。我對(duì) Python 的推薦是Fernet。
完成此操作后,您可以編寫一些秘密數(shù)據(jù)并生成密鑰,然后運(yùn)行腳本并將秘密數(shù)據(jù)返回給您:
$ echo "Very secret data" > secret.txt
$ dd if=/dev/urandom bs=1 count=32 > key.dat
32 bytes transferred
$ python so64569401.py
b'Very secret data\n'
然而,如上所述,這并不安全,因?yàn)閿?shù)據(jù)未經(jīng)身份驗(yàn)證;密文可以被篡改,并且您不會(huì)知道數(shù)據(jù)不是您放回的數(shù)據(jù)。例如,如果我刪除第一個(gè)加密調(diào)用,然后從加密文件中修改單個(gè)字節(jié)并再次運(yùn)行腳本:
$ hexf secret.txt.enc
$ python so64569401.py
b'Very secRet data\n'
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
def read_key(filename) -> bytes:
with open(filename, "rb") as f:
key = f.read(32)
assert len(key) == 32
return key
def encrypt_file(filename: str, key: bytes) -> str:
with open(filename, "rb") as f:
data = f.read()
cipher = AES.new(key, AES.MODE_CBC)
cipher_data = cipher.encrypt(pad(data, AES.block_size))
encrypted_filename = filename + ".enc"
with open(encrypted_filename, "wb") as f:
f.write(cipher.iv)
f.write(cipher_data)
return encrypted_filename
def decrypt_file(filename: str, key: bytes) -> bytes:
with open(filename, "rb") as f:
iv = f.read(AES.block_size)
cipher_data = f.read()
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
return unpad(cipher.decrypt(cipher_data), AES.block_size)
def main():
key = read_key("key.dat")
encrypted_filename = encrypt_file("secret.txt", key)
decrypted_data = decrypt_file(encrypted_filename, key)
print(decrypted_data)
if __name__ == "__main__":
main()
添加回答
舉報(bào)