花了二天的時間將AzDG可逆加密演算法改寫成Python
只在Python 2.6版上測試........
另外,針對台灣環境,
進行解密時,若數據源為Big5編碼的字串,會再轉成utf-8的編碼以便正常顯示中文。
#! /usr/bin/python # -*- coding: utf-8 -*- # python 2.6 import hashlib import sys import base64 import time default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) class AzDG: """docstring for AzDG""" cipher = '0123456789' charset = 'utf-8' def __init__(self, cipher = None): if cipher != None: self.cipher = cipher def getCipher(self): return self.cipher def cipherEncode(self, sourceText): cipherHash = hashlib.md5(self.getCipher()).hexdigest() cipherEncodeText = '' for i in range(len(sourceText)): cipherEncodeText = '%s%s' % (cipherEncodeText, chr(ord(sourceText[i]) ^ ord(cipherHash[i%32]))) print len(cipherEncodeText) return cipherEncodeText def encode(self, sourceText, charset = 'utf-8'): if charset != self.charset: sourceText = sourceText.encode(charset) #noise = hashlib.md5('%s' % (time.time())).hexdigest() noise = hashlib.md5('%s' % 1).hexdigest() encodeText = '' for i in range(len(sourceText)): encodeText = '%s%s%s' % (encodeText, noise[i%32], chr(ord(sourceText[i]) ^ ord(noise[i%32]))) return base64.b64encode(self.cipherEncode(encodeText)) def decode(self, sourceText, charset = 'utf-8'): decodeSourceText = self.cipherEncode(base64.b64decode(sourceText)) textLength = len(decodeSourceText) decodeText = '' i = 0 while i < textLength: decodeText = '{0}{1}'.format(decodeText, chr(ord(decodeSourceText[i]) ^ ord(decodeSourceText[i+1]))) i = i + 2 if self.charset != charset: decodeText = unicode(decodeText, charset).encode(self.charset) return decodeText#utf-8編碼
azdg = AzDG()
m = azdg.encode('中文測試')
print azdg.decode(m)
#big5編碼,下列字串解開後的值︰大5編碼許功蓋中文測試字
print azdg.decode('A6hTbQVgV+wMLlXnVVoOvV0PD/FaCAbqDw8HogLyAfEF7wXlA6lX6VbSVP1Wcw==','big5')
沒有留言:
張貼留言