查看网上很多都是抄袭的代码,大同小异,在前辈的基础上优化代码:
- 可自动补全16x字符串位数,解密后移除还原
- 优化加密后得到的数据码为base64,更易使用
3. 增加参数实例
4. 增强代码可读性
#!/usr/bin/env python #coding: utf-8 ‘‘‘ +-----------------------------------------------------------------------+ |Author: Cheng Wenfeng <[email protected]> | +-----------------------------------------------------------------------+ ‘‘‘ import sys import base64 import getopt from Crypto.Cipher import AES if len(sys.argv) < 2: print ‘Syntax: %s handle[encode|decode] str \n \ eg: %s encode [email protected]‘ % (sys.argv[0],sys.argv[0]) sys.exit() opts,args=getopt.getopt(sys.argv[1:], "h", [‘help‘]) for opt,arg in opts: if opt == ‘--help‘ or opt == ‘-h‘ : print ‘Syntax: %s handle[encode|decode] str \n \ eg: %s encode [email protected]‘ % (sys.argv[0],sys.argv[0]) sys.exit() Formatkey = ‘\0‘ FormatStr = lambda s: s+(16 - len(s)%16)*Formatkey key=‘qq277546922qqqqq‘ data=str(sys.argv[2]) def encode(key,data): keyIV=key obj = AES.new(key, AES.MODE_CBC,keyIV) ciphertext = base64.b64encode(obj.encrypt(FormatStr(data))) print ciphertext def decode(key,data): keyIV=key obj2 = AES.new(key, AES.MODE_CBC,keyIV) try: newmesg = obj2.decrypt(base64.b64decode(data)) print newmesg.replace(‘\0‘,‘‘) except TypeError: print ‘Decode Fail‘ if sys.argv[1]==‘encode‘: encode(key,data) elif sys.argv[1]==‘decode‘: decode(key,data) else : print ‘handle error‘ sys.exit() |