标题:Python版本的autocode加解密函数
只看楼主
好学
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
帖 子:622
专家分:318
注 册:2004-5-4
结帖率:50%
 问题点数:0 回复次数:1 
Python版本的autocode加解密函数
discuz里面有用到_authcode函数来实现可逆加密,做cookies加密和ucenter通信加密等需要用到本函数,下面是Python版本的_authcode函数:

程序代码:
#!/usr/bin/env python
# coding: utf-8
from hashlib import md5
import base64
from time import time
_auth_key = 'ASLDJSLSDds56IO898dKLKL'

def auth_code(string = '', operation = 'DECODE', key = '', expiry = 0):
    ckey_length = 4
    if not key: key = _auth_key
    key = md5(key).hexdigest()
    keya = md5(key[:16]).hexdigest()
    keyb = md5(key[16:]).hexdigest()
    if ckey_length:
        if operation == 'DECODE':
            keyc = string[:ckey_length]
        else:
            keyc = md5(str(time())).hexdigest()[-ckey_length:]
    else:
        keyc = ''
    cryptkey = keya + md5(keya + keyc).hexdigest()
    key_length = len(cryptkey)
   
    if operation == 'DECODE':
        string = base64.urlsafe_b64decode(string[ckey_length:])
    else:
        if expiry: expiry = expiry + time()
        expiry = '%010d' % expiry
        string = expiry + md5(string + keyb).hexdigest()[:16] + string
    string_length = len(string)
   
    result = ''
    box = range(256)
    rndkey = {}
    for i in range(256):
        rndkey[i] = ord(cryptkey[i % key_length])
   
    j = 0
    for i in range(256):
        j = (j + box[i] + rndkey[i]) % 256
        tmp = box[i]
        box[i] = box[j]
        box[j] = tmp
    a = 0
    j = 0
    for i in range(string_length):
        a = (a + 1) % 256
        j = (j + box[a]) % 256
        tmp = box[a]
        box[a] = box[j]
        box[j] = tmp
        result += chr(ord(string[i]) ^ (box[(box[a] + box[j]) % 256]))
    if operation == 'DECODE':
        if result[:10] == 0 or int(result[:10]) - time() > 0 or result[10:26] == md5(result[26:] + keyb).hexdigest()[:16]:
            return result[26:]
        else:
            return ''
    else:
        return keyc + base64.urlsafe_b64encode(result) #replace('=', '')

str1 = 'hello world !!!'
encode_str = auth_code(str1, 'ENCODE') #加密
print encode_str
print auth_code(encode_str) #解密

使用本函数即可实现Python编写的网站与PHP编写的网站同步登陆


[ 本帖最后由 好学 于 2010-3-24 02:48 编辑 ]
搜索更多相关主题的帖子: 解密 函数 autocode Python 
2010-03-24 02:45
yangfanconan
Rank: 7Rank: 7Rank: 7
等 级:贵宾
威 望:10
帖 子:397
专家分:541
注 册:2009-9-22
得分:0 
学习了
2010-04-03 08:41



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-300363-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.458240 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved