- 任务1:定义生成随机密钥的函数。函数带有一个参数L;函数生成一个包含L个字节的随机字节串(可以借助secrets包中的token_bytes模块实现),并将随机字节串转换成整数返回。
任务2:定义实现加密单元的函数。函数带有一个字符串参数;函数将字符串编码为字节串并转换为整数,然后将它与一个随机密钥进行异或运算生成密文,最后将密文和随机密钥返回。
任务3:定义实现解密单元的函数。函数带有两个参数,分别是任务2中函数返回的密文和密钥。函数将密文和密钥进行异或运算,然后计算密文的长度,最后返回解密后的字符串。
任务4:利用上面定义的三个函数,对下面两个字符串进行加解密操作。
string1 = “路漫漫其修远兮,吾将上下而求索。”
string2 = “Never put off until tomorrow what may be done today.”
任务5:利用json 模块和pathlib包中的Path模块,分别定义一个加密文本文件的函数和一个解密文本文件的函数。
实验步骤:
1.首先将文本文件转换为二进制数,再生成与该二进制数等长的随机密钥,将二进制数与密钥进行异或操作,得到加密后的二进制数。
2. 解密操作
将加密后的二进制文件与密钥进行异或操作,得到原来的二进制数,再将二进制数恢复成文本文件。
实验结果:
import secrets
from pathlib import Path
#全局变量
#################################################################
#################################################################
mypath='E:\\'# 输入你的文件路径(文件名不输入)
textname='test.txt'# 输入你要加密的文件名
#################################################################
#################################################################
def product_key(L):
key=int.from_bytes(secrets.token_bytes(L),byteorder='big')
return key
def enc(string):
#str to byte to int
txt=int.from_bytes(bytes(string,encoding = "utf-8"),byteorder='big')
key=product_key(len(str(txt)))
secret=txt^key
return secret,key
def dec(secret,key):
message=secret^key
length=len(str(message))
message=int.to_bytes(message,length,'big')
message=bytes.decode(message,encoding='utf-8', errors='strict')
#message=str(message)
return message
def enc_txtfile():
file=Path(mypath+textname)
if file.exists() is False:
return 'test.txt is not found'
else:
string=file.read_text(encoding = 'utf-8')#utf-8:可以录入中文
secret=enc(string)
#new a file
new_file=open(mypath+'enc_txt.txt','w')#新建txt文件
new_file.close()
new_file=Path(mypath+'enc_txt.txt')
new_file.write_text(str(secret[0])+'\n'+str(secret[1]))#第一行写入密文,第二行写入等长随机整数
return '加密结果:\n'+str(secret[0])+'\n密钥:\n'+str(secret[1])
def dec_txtfile():
file=Path(mypath+'enc_txt.txt')
if file.exists is False:
return 'enc_txt is not found'
else:
secret=file.read_text()
length=len(secret)
message=dec(int(secret[0:length//2]),int(secret[length//2+1:]))
message=message.strip().strip(b'\x00'.decode())#去除不可见字符 \x00
new_file=open(mypath+'dec_txt.txt','w')#新建txt文件
new_file.close()
new_file=Path(mypath+'dec_txt.txt')
new_file.write_text(message)
return '解密结果:\n'+message
print(enc_txtfile())
print(dec_txtfile())