本文實(shí)例講述了Python實(shí)現(xiàn)的文本簡單可逆加密算法。分享給大家供大家參考,具體如下:
其實(shí)很簡單,就是把一段文本每個(gè)字符都通過某種方式改變(比如加1)
這樣就實(shí)現(xiàn)了文本的加密操作,解密就是其逆運(yùn)算
# -*-coding:utf-8 -*-import sysreload(sys)sys.setdefaultencoding('utf8')#加密def jiami(): filename=raw_input('please input file:/n') while True: try: password=int(raw_input('input number pass word:/n')) break except: print 'please input number:/n' fileword=open(filename,'r') num=filename.rfind('.') newfilename=filename[:num]+'[加密]'.encode('gbk')+filename[num:] content=fileword.read(1) newfileword=open(newfilename,'a+') while len(content)>0: contentInt=ord(content) newContent=contentInt+password c=chr(newContent) newfileword.write(c) content=fileword.read(1) newfileword.close() fileword.close()#解密def jiemi(): filename=raw_input('please input file:/n') while True: try: password=int(raw_input('input number pass word:/n')) break except: print 'please input number:/n' fileword=open(filename,'r') num=filename.rfind('.') num2=filename.rfind('[') newfilename=filename[:num2]+'[解密]'.encode('gbk')+filename[num:] content=fileword.read(1) newfileword=open(newfilename,'a+') while len(content)>0: contentInt=ord(content) newContent=contentInt-password c=chr(newContent) newfileword.write(c) content=fileword.read(1) newfileword.close() fileword.close()while True: index=int(raw_input('---請(qǐng)輸入命令,1為加密 2為解密 3為退出---/n'.encode('gbk'))) if index==1: jiami() elif index==2: jiemi() elif index==3: exit(0)else: pass注意:
①如果出現(xiàn)中文編碼問題可以通過.encode,.decode編碼解碼
②可以通過Python的切片操作處理文件名,很方便,例如: newfilename=filename[:num]+'[加密]'.encode('gbk')+filename[num:]
③最重要的!!本加密方法只是簡單的給文本字符做一個(gè)+password處理,其方法非常不合理,因?yàn)榧拥臄?shù)如果過大會(huì)造成chr字節(jié)不夠(比如你輸一個(gè)1000)
所以本代碼只適用于新手練習(xí),而不能作為真正的處理算法
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選