1. 编写一个程序,将一段文字写入磁盘文件《姓名》.dat保存起来。要求文件的第一部分保存文件的结构(含密钥的变形码),第二部分是文字用密钥加密的密文。文件被重新打开时要求输入密码并验证密码并限定密码的输入次数。
时间: 2024-03-19 16:46:06 浏览: 11
以下是一个简单的Python程序实现上述功能:
```python
import os
import hashlib
from Crypto.Cipher import AES
# 加密函数
def encrypt(key, text):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(text.encode('utf-8'))
return nonce + ciphertext + tag
# 解密函数
def decrypt(key, ciphertext):
nonce = ciphertext[:16]
tag = ciphertext[-16:]
ciphertext = ciphertext[16:-16]
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)
try:
cipher.verify(tag)
return plaintext.decode('utf-8')
except:
return None
# 保存文件
def save_file(filename, key, text):
# 生成密钥的变形码
hasher = hashlib.sha256()
hasher.update(key.encode('utf-8'))
iv = hasher.digest()[:16]
# 加密
ciphertext = encrypt(key.encode('utf-8'), text)
# 写入文件
with open(filename, 'wb') as f:
# 写入变形码和加密后的密文
f.write(iv + ciphertext)
# 读取文件
def read_file(filename, key):
# 读取文件
with open(filename, 'rb') as f:
data = f.read()
# 获取变形码和密文
iv = data[:16]
ciphertext = data[16:]
# 解密
plaintext = decrypt(key.encode('utf-8'), ciphertext)
return plaintext
# 主函数
def main():
filename = input("请输入文件名(不含后缀):") + ".dat"
key = input("请输入密码:")
text = input("请输入要保存的文字:")
# 保存文件
save_file(filename, key, text)
# 读取文件
for i in range(3):
password = input("请输入密码进行验证(还有%d次机会):" % (3-i))
plaintext = read_file(filename, password)
if plaintext is not None:
print("解密后的内容为:", plaintext)
break
else:
print("密码错误,请重新输入。")
else:
print("密码输入错误次数过多,文件已被锁定。")
if __name__ == '__main__':
main()
```
该程序使用了AES对称加密算法和SHA256哈希算法进行加密和解密。在保存文件时,程序会生成一个密钥的变形码,将变形码和加密后的密文一起写入文件。在读取文件时,程序会先读取变形码和密文,然后根据用户输入的密码解密密文,如果密码错误则限制输入次数,超过次数则锁定文件。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)