要给文件加密和解密,可以使用Python中的加密模块如cryptography或PyCrypto
要给文件加密和解密,可以使用Python中的加密模块如cryptography
或PyCrypto
。以下是一个使用PyCrypto
模块进行文件加密和解密的示例代码:
fromCrypto.CipherimportAES
fromCrypto.Randomimportget_random_bytes
defencrypt_file(input_file,output_file,key):
cipher=AES.new(key,AES.MODE_EAX)
withopen(input_file,'rb')asf_in:
data=f_in.read()
nonce=cipher.nonce
ciphertext,tag=cipher.encrypt_and_digest(data)
withopen(output_file,'wb')asf_out:
f_out.write(nonce)
f_out.write(tag)
f_out.write(ciphertext)
defdecrypt_file(input_file,output_file,key):
withopen(input_file,'rb')asf_in:
nonce=f_in.read(16)
tag=f_in.read(16)
ciphertext=f_in.read()
cipher=AES.new(key,AES.MODE_EAX,nonce=nonce)
data=cipher.decrypt_and_verify(ciphertext,tag)
withopen(output_file,'wb')asf_out:
f_out.write(data)
#Generatearandomkey
key=get_random_bytes(16)
#Encryptafile
encrypt_file('input.txt','encrypted.txt',key)
#Decrypttheencryptedfile
decrypt_file('encrypted.txt','output.txt',key)
在上面的示例中,我们首先使用encrypt_file()
函数对输入文件进行加密,然后使用decrypt_file()
函数对加密后的文件进行解密。在加密和解密过程中,我们使用AES加密算法和随机生成的16字节密钥。
请注意,加密和解密文件时,务必保管好密钥,以便正确解密文件。
版权声明
本文仅代表作者观点,不代表博信信息网立场。