教你用python實現一個加密的文字處理器
這是一個類似於記事本的文字處理器。與正常的記事本不同的是,它會將文本文檔進行加密,確保無法被常規的程序打開。
由於本人是一位業餘編程愛好者,對於“python之禪”之類的規則比較不以為然,因此本程序代碼也許有些許凌亂(當然不利於後期修改)。
這篇文章我早已發佈過,但當時隻給出瞭代碼,並加瞭一些註釋。現在,我希望在這裡詳細解釋這個程序。我會分一個月或更久更新這篇文章,請讀者耐心等待。
首先,對於一個適合我們廣大中華兒女使用的程序,我們不可避免地要使用中文。這就需要對編碼進行聲明:
# coding:utf-8
然後,就到瞭模塊導入的環節瞭。我們這裡需要tkinter,windnd,os和sys。windnd可以用pip安裝,tkinter則需要在安裝python時勾選:
from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import * import windnd import os import sys
接下來,我們會看到這樣一段代碼:
try: filename = sys.argv[1] except: filename = ""
這是幹什麼的呢?我們知道,對於exe程序,有一個“Open with”功能,也就是可以將拖動到exe文件或其快捷方式的文件打開。事實上,py文件也有這個功能,但是多數情況下這樣操作後隻能使程序正常運行,而不能對文件進行任何操作。而“sys.argv[1]”的作用就是,讀取這個文件的路徑信息。這樣,我們就可以用open或sys庫裡的一些指令進行對文件的操作瞭。
def encryption(c, d): c = list(c + d) g=list(d) d=0 for i in g: d*=ord(i) d=round(abs(d)**0.5) f="0x" for i in c: e=str(ord(i)+d) d=round(300*(d**0.5)) f=f+e+"a" f=eval(f[:-1]) return (f) def decrypt(c,d): c=hex(int(c)) print(c) c=c[2:].split("a") z=d g = list(d) d = 0 for i in g: d *= ord(i) d = round(abs(d) ** 0.5) f="" for i in c: e = chr(int(i)-d) d = round(300 * (d ** 0.5)) f = f + e if f[-len(z):]==z: f=f[:-len(z)] return (f) else: c="bbc"+12
這一段就比較勁爆瞭。它定義瞭兩個函數,一個用於加密,另外一個用於解密(順便說一句,我英語不太好,有的函數或變量的名字可能比較古怪,請見諒)。
encryption是加密的函數(呃,這個應該叫做encrypt,我編這個程序時大腦有些短路,但既然已經這樣瞭,也就不改瞭),它會將明文(輸入的c)通過與密鑰d有關的某些運算,得出一個十六進制數,然後將其轉化為十進制。同時,為瞭確保解密結果唯一,將密鑰一起連接在明文上,起校驗作用。在這裡,對於明文的每一個字符都會將加密過程中實際使用的密鑰進行變動,因此基本是不可能通過字符出現頻率的規律來破解的。由於密鑰是字符,暴力拆解也基本不可能。
decrypt是解密,它大致就是encryption的逆操作,同時如果校驗的結果有誤,或是遇到其他解密失敗的情況它會產生錯誤(因此使用時需要try-except,來確保程序不會退出,同時對解密失敗的情況進行處理)。
接下來是基本的文件操作部分:
def mynew(aaa=1): global top, filename, textPad top.title("無標題 - 加密文本編輯器") filename = None textPad.delete(1.0, END) textPad.insert(1.0, "") def myopen(aaa=1): global filename,kkk filename = askopenfilename() if filename == "": filename = None else: top.title(os.path.basename(filename)+" - 加密文本編輯器") format=os.path.basename(filename)[os.path.basename(filename).find(".")+1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\","") textPad.insert(1.0,decrypt(ccc,format)) kkk=1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk=0 f.close() def mysave(aaa=1): global filename,kkk try: msg = textPad.get(1.0, 'end')[0:-1] if kkk==0: f = open(filename, 'w', encoding="utf-8") f.write(msg) else: f = open(filename, 'wb') fffff = str(encryption(msg, format)) fffff = eval("b'{}'".format(fffff)) print(fffff) f.write(fffff) f.close() except: mysaveas() def mysaveas(aaa=1): global filename f = asksaveasfilename(initialfile="無標題.txt") filename = f format = os.path.basename(filename)[os.path.basename(filename).find(".") + 1:] msg = textPad.get(1.0, 'end')[0:-1] if not format == "py" and not format=="bat" and not format == "pyw"and not format == "cmd": fh = open(filename, 'wb') fffff = str(encryption(msg, format)) fffff = eval("b'{}'".format(fffff)) print(fffff) fh.write(fffff) else: fh = open(filename, 'w', encoding="utf-8") fh.write(msg) fh.close() top.title(os.path.basename(f)+" - 加密文本編輯器") def opened(files): global filename,kkk ff = '\n'.join((item.decode('gbk') for item in files)) filename = ff if filename == "": filename = None else: top.title(os.path.basename(filename) + " - 加密文本編輯器") format = os.path.basename(filename)[os.path.basename(filename).find(".") + 1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\", "") textPad.insert(1.0, decrypt(ccc, format)) kkk = 1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk = 0 f.close() def mynew(aaa=1): global top, filename, textPad top.title("無標題 - 加密文本編輯器") filename = None textPad.delete(1.0, END) textPad.insert(1.0, "")
首先說mynew。這裡有一個可選參數a,這是因為通過bind激活函數會輸入一個參數(這點我非常反感),為瞭不讓程序運行出錯,就添加瞭一個可選參數。這個其實沒啥好說。global後面是所需的全局變量,然後就是設置窗口名稱、文件名稱,並清空輸入框,很簡單,很明瞭。
def myopen(aaa=1): global filename,kkk filename = askopenfilename() if filename == "": filename = None else: top.title(os.path.basename(filename)+" - 加密文本編輯器") format=os.path.basename(filename)[os.path.basename(filename).find(".")+1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\","") textPad.insert(1.0,decrypt(ccc,format)) kkk=1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk=0 f.close()
然後就是myopen。“filename=askopenfilename()”就是,彈出一個選擇打開的文件的窗口,並將結果存入filename。然後我們獲取文件的後綴信息,作為解密所需的密鑰。接下來,我們先嘗試解密文件。如果執行中有錯誤,也就是無法解密,則用gbk編碼正常打開,仍然打開失敗,則使用utf-8。當然,如果都失敗瞭,就用rb模式,也就是字節流的形式打開。
啊,越講越上頭,超過瞭我預期的篇幅……好瞭,現在先講到這裡,等待下一次更新吧(本人初二,因此接觸電腦機會不多,更新嘛,自然是比較慢的。耐心等待!耐心等待!!!)!
完整的代碼:
# coding:utf-8 from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import * import windnd import os import sys kkk=1 try: filename = sys.argv[1] except: filename = "" def encryption(c, d): c = list(c + d) g=list(d) d=0 for i in g: d*=ord(i) d=round(abs(d)**0.5) f="0x" for i in c: e=str(ord(i)+d) d=round(300*(d**0.5)) f=f+e+"a" f=eval(f[:-1]) return (f) def decrypt(c,d): c=hex(int(c)) print(c) c=c[2:].split("a") z=d g = list(d) d = 0 for i in g: d *= ord(i) d = round(abs(d) ** 0.5) f="" for i in c: e = chr(int(i)-d) d = round(300 * (d ** 0.5)) f = f + e if f[-len(z):]==z: f=f[:-len(z)] return (f) else: c="bbc"+12 def mynew(aaa=1): global top, filename, textPad top.title("無標題 - 加密文本編輯器") filename = None textPad.delete(1.0, END) textPad.insert(1.0, "") def myopen(aaa=1): global filename,kkk filename = askopenfilename() if filename == "": filename = None else: top.title(os.path.basename(filename)+" - 加密文本編輯器") format=os.path.basename(filename)[os.path.basename(filename).find(".")+1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\","") textPad.insert(1.0,decrypt(ccc,format)) kkk=1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk=0 f.close() def mysave(aaa=1): global filename,kkk try: msg = textPad.get(1.0, 'end')[0:-1] if kkk==0: f = open(filename, 'w', encoding="utf-8") f.write(msg) else: f = open(filename, 'wb') fffff = str(encryption(msg, format)) fffff = eval("b'{}'".format(fffff)) print(fffff) f.write(fffff) f.close() except: mysaveas() def mysaveas(aaa=1): global filename f = asksaveasfilename(initialfile="無標題.txt") filename = f format = os.path.basename(filename)[os.path.basename(filename).find(".") + 1:] msg = textPad.get(1.0, 'end')[0:-1] if not format == "py" and not format=="bat" and not format == "pyw"and not format == "cmd": fh = open(filename, 'wb') fffff = str(encryption(msg, format)) fffff = eval("b'{}'".format(fffff)) print(fffff) fh.write(fffff) else: fh = open(filename, 'w', encoding="utf-8") fh.write(msg) fh.close() top.title(os.path.basename(f)+" - 加密文本編輯器") def opened(files): global filename,kkk ff = '\n'.join((item.decode('gbk') for item in files)) filename = ff if filename == "": filename = None else: top.title(os.path.basename(filename) + " - 加密文本編輯器") format = os.path.basename(filename)[os.path.basename(filename).find(".") + 1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\", "") textPad.insert(1.0, decrypt(ccc, format)) kkk = 1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk = 0 f.close() top = Tk() top.title("無標題 - 加密文本編輯器") top.geometry("1000x600+100+50") menubar = Menu(top) menubar.add_command(label="新建", command=mynew) menubar.add_command(label="打開", command=myopen) menubar.add_command(label="保存", command=mysave) menubar.add_command(label="另存為", command=mysaveas) menu = Menu(top, tearoff=False) menu.add_command(label="新建", accelerator="Ctrl+N", command=mynew) menu.add_command(label="打開", accelerator="Ctrl+O", command=myopen) menu.add_command(label="保存", accelerator="Ctrl+S", command=mysave) menu.add_command(label="另存為", accelerator="Ctrl+Shift+S", command=mysaveas) def command(event): menu.post(event.x_root, event.y_root) top['menu'] = menubar all=Frame(top) all.pack(expand=YES, fill=BOTH) textPad = Text(all,font=('宋體', 14), undo=True) if filename == "": filename = None textPad.insert(1.0, "") else: top.title(os.path.basename(filename) + " - 加密文本編輯器") format = os.path.basename(filename)[os.path.basename(filename).find(".") + 1:] textPad.delete(1.0, END) try: f = open(filename, 'rb') c = f.read() ccc = str(c)[2:-1] ccc.replace("\\", "") textPad.insert(1.0, decrypt(ccc, format)) kkk = 1 except: f.close() try: f = open(filename, 'r', encoding="gbk") try: c = f.read() except: f.close() f = open(filename, 'r', encoding="utf-8") c = f.read() textPad.insert(1.0, c) kkk = 0 except: f.close() f = open(filename, 'rb') c = f.read() textPad.insert(1.0, c) kkk = 0 f.close() scroll = Scrollbar(all) textPad.config(yscrollcommand=scroll.set) scroll.config(command=textPad.yview) scroll.pack(side=RIGHT, fill=Y) textPad.pack(expand=YES,side=RIGHT,fill=BOTH) top.bind("<Control-N>", mynew) top.bind("<Control-n>", mynew) top.bind("<Control-O>", myopen) top.bind("<Control-o>", myopen) top.bind("<Control-S>", mysave) top.bind("<Control-s>", mysave) top.bind("<Control-Shift-S>", mysaveas) top.bind("<Control-Shift-s>", mysaveas) top.bind("<Button-3>", command) windnd.hook_dropfiles(top,func=opened) top.mainloop()
總結
到此這篇關於用python實現一個加密文字處理器的文章就介紹到這瞭,更多相關python加密文字處理器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- python實現記事本功能
- Python簡單的GUI程序示例詳解
- 教你如何使用Python Tkinter庫制作記事本
- 如何使用python批量修改文本文件編碼格式
- 基於Python制作AI聊天軟件的示例代碼