Python PyCryptome cipher.encrypt将空白文本保存到加密文件
我在加密路径accountfile处的文件内容时遇到很多问题。 加密确实有效,因为解密成功地将保存路径的版本的accountfile的路径输出到文件中。代码在没有错误的情况下成功运行,但保存的加密文件在加密时最终为空。如何成功加密ptext的内容Python PyCryptome cipher.encrypt将空白文本保存到加密文件,python,encryption,pycryptodome,Python,Encryption,Pycryptodome,我在加密路径accountfile处的文件内容时遇到很多问题。 加密确实有效,因为解密成功地将保存路径的版本的accountfile的路径输出到文件中。代码在没有错误的情况下成功运行,但保存的加密文件在加密时最终为空。如何成功加密ptext的内容 def encrypt_account(path, filename, accountfile): c_file = PurePath(path).parent / (PurePath(filename).parent.name + "
def encrypt_account(path, filename, accountfile):
c_file = PurePath(path).parent / (PurePath(filename).parent.name + "c.txt")
file3 = open(c_file, 'rb')
byteskey = file3.read(32)
file3.close()
ckey = bytes(byteskey)
cipher = AES.new(ckey, AES.MODE_CBC)
ptext = open(str(accountfile)).read()# this is the account file
ciphertext = cipher.encrypt(pad(bytes(ptext, "utf-8"), AES.block_size))
with open(str(path.parent / accountfile.stem) + ".enc", 'wb')as c_file:
c_file.write(cipher.iv)
c_file.write(ciphertext)
#c_file.close()
#os.remove(accountfile)
这里有一个确实有效的示例,但请不要将其用于任何敏感的内容,因为它不安全。 正确使用加密原语是困难的;相反,您应该使用比您和我更聪明的人编写并认证的更高级别的食谱,这些食谱在正确使用时是安全的。我对Python的建议是 这样,您就可以编写一些机密数据并生成密钥,然后运行脚本并将机密数据返回给您:
$ 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'
然而,如上所述,这是不安全的,因为数据没有经过身份验证;密文可以被篡改,你不会知道数据不是你放回的。例如,如果删除第一个加密调用,则修改加密文件中的一个字节,然后再次运行脚本:
$ hexf secret.txt.enc
$ python so64569401.py
b'Very secRet data\n'
您是否尝试过
print()。我觉得自己像个白痴!我忘记关闭调用此函数的函数中的filestream。非常感谢你的帮助!尽管如此,请看我的回答(并注意其中的警告)。我完全理解。这是一个加密类-它不打算用于任何关键的地方,只是为了表明我理解这些概念。
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()