将文件f1.txt的内容加密(加密算法自己设计)后存放到f2.txt中。读出f2.txt文件的内容,并显示解密后的内容。
时间: 2023-04-26 14:06:34 浏览: 46
好的,以下是回复:
可以使用对称加密算法,比如AES加密算法,将文件f1.txt的内容加密后存放到f2.txt中。读出f2.txt文件的内容,再使用相同的密钥和算法进行解密,即可得到原始的文件内容。
具体实现可以使用Python的加密库,比如pycryptodome库,示例代码如下:
```python
from Crypto.Cipher import AES
# 加密函数
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
iv = b'0123456789abcdef' # 初始化向量
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
# 解密函数
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
# 使用示例
key = b'mysecretpassword' # 密钥
encrypt_file(key, 'f1.txt', 'f2.txt') # 加密f1.txt并存储到f2.txt中
decrypt_file(key, 'f2.txt', 'f1_decrypted.txt') # 解密f2.txt并存储到f1_decrypted.txt中
```
以上代码中,encrypt_file函数用于加密文件,decrypt_file函数用于解密文件。其中,key为密钥,in_filename为输入文件名,out_filename为输出文件名(默认为输入文件名加上.enc后缀),chunksize为每次读取文件的块大小。加密过程中,先写入文件大小和初始化向量,然后对每个块进行加密并写入输出文件中;解密过程中,先读取文件大小和初始化向量,然后对每个块进行解密并写入输出文件中,最后截断输出文件到原始大小。
希望能对您有所帮助!