AzDG可逆加密演算法 for Python,azdgpython,花了二天的時間將AzDG


花了二天的時間將AzDG可逆加密演算法改寫成Python只在Python2.6版上測試........另外,針對台灣環境,進行解密時,若數據源為Big5或GB2312編碼的字串,會再轉成utf-8的編碼以便正常顯示中文。http://jian-zhoung.blogspot.com/

[Python]代码

#! /usr/bin/python# -*- coding: utf-8 -*-# python 2.6import hashlibimport sysimport base64import timedefault_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])))        return cipherEncodeText    def encode(self, sourceText, charset = 'utf-8'):        if charset != self.charset:            sourceText = sourceText.encode(charset)        noise = hashlib.md5('%s' % (time.time())).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 charset != self.charset:            decodeText =  unicode(decodeText, charset).encode(self.charset)        return decodeTextazdg = AzDG()m = azdg.encode('中文測試')print azdg.decode(m)#不同的編碼之間也可進行解碼,GB2312也行print azdg.decode('A6hTbQVgV+wMLlXnVVoOvV0PD/FaCAbqDw8HogLyAfEF7wXlA6lX6VbSVP1Wcw==','big5')

评论关闭