# -* -coding: UTF-8 -* - # 功能:異或方式對文件進行加密和解密 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) # os.path.sep爲操做系統的文件分隔符 fileName = fileFullName[len(fileFullName) - 1].split(".")[0] fileSuffix = fileFullName[len(fileFullName) - 1].split(".")[1] # print("文件全名稱:",fileFullName[len(fileFullName)-1]) # print("文件名稱:",fileName) # print("文件後綴:",fileSuffix) fileParent = path[0:len(path) - len(fileFullName[len(fileFullName) - 1])] newFileName = "加密_" + fileFullName[len(fileFullName) - 1] newFilePath = fileParent + newFileName # print("文件父路徑:",fileParent) # print("新的文件名稱:",newFileName) # print("新的文件全路徑:", newFilePath) 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) # os.path.sep爲操做系統的文件分隔符 fileName = fileFullName[len(fileFullName) - 1].split(".")[0] fileSuffix = fileFullName[len(fileFullName) - 1].split(".")[1] # print("文件全名稱:", fileFullName[len(fileFullName)-1]) # print("文件名稱:", fileName) # print("文件後綴:", fileSuffix) fileParent = path[0:len(path) - len(fileFullName[len(fileFullName) - 1])] newFileName = "解密_" + fileFullName[len(fileFullName) - 1] newFilePath = fileParent + newFileName # print("文件父路徑:", fileParent) # print("新的文件名稱:", newFileName) # print("新的文件全路徑:", newFilePath) 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()