Python實現的文本簡單可逆加密算法示例
本文實例講述了Python實現的文本簡單可逆加密算法。分享給大家供大家參考,具體如下:
其實很簡單,就是把一段文本每個字符都通過某種方式改變(比如加1)
這樣就實現了文本的加密操作,解密就是其逆運算
# -*-coding:utf-8 -*-
import sys
reload(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('---請輸入命令,1為加密 2為解密 3為退出---\n'.encode('gbk')))
if index==1:
jiami()
elif index==2:
jiemi()
elif index==3:
exit(0)
else:
pass
注意:
①如果出現中文編碼問題可以通過.encode,.decode編碼解碼
②可以通過Python的切片操作處理文件名,很方便,例如: newfilename=filename[:num]+'[加密]'.encode('gbk')+filename[num:]
③最重要的??!本加密方法只是簡單的給文本字符做一個+password處理,其方法非常不合理,因為加的數如果過大會造成chr字節(jié)不夠(比如你輸一個1000)
所以本代碼只適用于新手練習,而不能作為真正的處理算法
PS:關于加密解密感興趣的朋友還可以參考本站在線工具:
MD5在線加密工具:
http://tools.jb51.net/password/CreateMD5Password
迅雷、快車、旋風URL加密/解密工具:
http://tools.jb51.net/password/urlrethunder
在線散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
在線sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python打包工具PyInstaller的安裝與pycharm配置支持PyInstaller詳細方法
這篇文章主要介紹了Python打包工具PyInstaller的安裝與pycharm配置支持PyInstaller詳細方法,需要的朋友可以參考下2020-02-02

