import os
import datetime
def main():
getInput()
def getInput():
while(True):
oper = input("请输入操作(e:加密 d:解密):")
if(oper == "e" or oper == "d"):
break
else:
print("输入有误,请重新输入!")
while(True):
password = input("请输入密码:")
if(len(password) == 0):
print("密码不能为空!")
else:
break
while(True):
path = input("请输入文件路径(示例:C:\test.txt):")
try:
f_read = open(path, "rb")
except:
print("文件没有找到,请检查路径是否存在!")
else:
break
if(oper == "e"):
encrypt(path, password)
elif(oper == "d"):
decrypt(path, password)
def encrypt(path, password):
start = datetime.datetime.now()
fileFullName = path.split(os.path.sep)
fileName = fileFullName[len(fileFullName) - 1].split(".")[0]
fileSuffix = fileFullName[len(fileFullName) - 1].split(".")[1]
fileParent = path[0:len(path) - len(fileFullName[len(fileFullName) - 1])]
newFileName = "加密_" + fileFullName[len(fileFullName) - 1]
newFilePath = fileParent + newFileName
f_read = open(path, "rb")
f_write = open(newFilePath, "wb")
count = 0
for now in f_read:
for nowByte in now:
newByte = nowByte ^ ord(password[count % len(password)])
count += 1
f_write.write(bytes([newByte]))
f_read.close()
f_write.close()
end = datetime.datetime.now()
print("文件加密完毕^_^", (end - start))
def decrypt(path, password):
start = datetime.datetime.now()
fileFullName = path.split(os.path.sep)
fileName = fileFullName[len(fileFullName) - 1].split(".")[0]
fileSuffix = fileFullName[len(fileFullName) - 1].split(".")[1]
fileParent = path[0:len(path) - len(fileFullName[len(fileFullName) - 1])]
newFileName = "解密_" + fileFullName[len(fileFullName) - 1]
newFilePath = fileParent + newFileName
f_read = open(path, "rb")
f_write = open(newFilePath, "wb")
count = 0
for now in f_read:
for nowByte in now:
newByte = nowByte ^ ord(password[count % len(password)])
count += 1
f_write.write(bytes([newByte]))
f_read.close()
f_write.close()
end = datetime.datetime.now()
print("文件解密完毕", (end - start))
main()