Python使用‘异或’对文本进行加密
#初始密码
password="hello"
#需处理的文本
text="abcdefjhigk"
#密码初始长度
pwdLen=len(password)
#文本长度
textLen=len(text)
#处理生成秘钥,每个字符与需处理文本一一对应
key=textLen//pwdLen*password+password[:textLen%pwdLen]
list=[]
for i in range(len(key)):
textBytes=bytes(key,"ASCII")[i]^bytes(text,"ASCII")[i]#转换成二进制格式一对一异或处理
list.append(chr(textBytes))#转换成字符格式
#将字符数组串联起来生成加密字符
text01="".join(list)
#解密
list1=[]
for i in range(len(key)):
textBytes=bytes(key,"ASCII")[i]^bytes(text01,"ASCII")[i]#转换成二进制格式一对一异或处理
list1.append(chr(textBytes))#转换成字符格式
text02="".join(list1)
print(text02)
运行结果为:
abcdefjhigk#与原文本相同
对视频文件加密
import time
time_start=time.time()#生成开始时间
#需要加密的文件路径
fildPath=r"D:\连续剧\100.mp4"
picRead=open(fildPath,mode="rb")
#读取二进制文件
picData=picRead.read()
picLen=len(picData)
#需要写出的文件路径
f_write = open(r"D:\连续剧\101.mp4","wb")
#提供密码的txt文件
keyPath=r"C:\Users\liubb\Pictures\key.txt"
keyRead=open(keyPath,mode="rb")
#读取二进制密钥文件
keyData=keyRead.read()
keyLen=keyData.__len__()
#获取Key
key=picLen//keyLen*keyData+keyData[:picLen%keyLen]
#进行循环加密
for i in range(len(key)):
newByte=key[i]^picData[i]
#写出二进制文件
f_write.write(bytes([newByte]))
f_write.close()
picRead.close()
keyRead.close()
time_end=time.time()#生成结束时间
print('time cost',time_end-time_start,'s')#打印运行时间
解密就是把输出路径改为输入路径即可