1) 写一个加密程序,对文件1txt进行加密。它从输入流中读入一个密钥,并将文件密文输出。采用下面的简单加密算法: 1)读入密钥的key是一个字符串; 2)明文中字符c的密文为c^key[i]; 3)循环使用key中的各个字符,直至处理完全部明文。如果key为空,则不作加密 4)解密时,用同一个key重新加密密文,就可以得到明文。
时间: 2024-02-13 19:07:54 浏览: 17
好的,这个加密程序可以用Python实现。以下是代码示例:
```python
def encrypt_file(input_file, output_file, key):
with open(input_file, 'r') as f:
plaintext = f.read()
if not key:
# 如果key为空,则不作加密,直接输出明文
ciphertext = plaintext
else:
# 对明文进行加密
key_len = len(key)
ciphertext = ''
for i, c in enumerate(plaintext):
# 循环使用key中的各个字符,直至处理完全部明文
key_char = key[i % key_len]
ciphertext += chr(ord(c) ^ ord(key_char))
with open(output_file, 'w') as f:
f.write(ciphertext)
print('加密成功!')
def decrypt_file(input_file, output_file, key):
with open(input_file, 'r') as f:
ciphertext = f.read()
if not key:
# 如果key为空,则不作解密,直接输出密文
plaintext = ciphertext
else:
# 对密文进行解密
key_len = len(key)
plaintext = ''
for i, c in enumerate(ciphertext):
# 循环使用key中的各个字符,直至处理完全部密文
key_char = key[i % key_len]
plaintext += chr(ord(c) ^ ord(key_char))
with open(output_file, 'w') as f:
f.write(plaintext)
print('解密成功!')
```
你可以调用 `encrypt_file()` 函数来加密文件,调用 `decrypt_file()` 函数来解密文件。这两个函数都需要传入三个参数:输入文件名、输出文件名和密钥。注意,输入文件和输出文件必须是文本文件(.txt),否则可能会出现乱码。