本文实例讲述了python实现简单的可逆加密程序。分享给大家供大家参考。具体如下:
python代码如下:
代码如下:
#coding=utf-8
””’
description: 可逆的加密与解密
environment: python2.5.x
author:idehong@gmail.com
”’
import os
import sys
class code(object):
””’可逆的加密与解密”’
def __init__(self, key = “idehong@gmail.com”):
self.__src_key = key
self.__key = self.__get_strascii(self.__src_key, true)
def encode(self, value):
””’加密函数, 加密后为一串数字”’
return “%d” % (self.__get_strascii(value, true) ^ self.__key)
def decode(self, pwd):
””’解密函数”’
if self.is_number(pwd):
return self.__get_strascii( (int(pwd)) ^ self.__key, false )
else:
print ‘require number.’
def reset_key(self, key):
””’重新设置key”’
self.__src_key = key
self.__key = self.__get_strascii(self.__src_key, true)
#===============================================================================
# 内部调用接口
#===============================================================================
def __get_strascii(self, value, bflag):
if bflag:
return self.__get_str2ascii(value)
else:
return self.__get_ascii2str(value)
def __get_str2ascii(self, value):
ls = []
for i in value:
ls.append( self.__get_char2ascii( i ) )
return long(“”.join(ls))
def __get_char2ascii(self, char):
””’获取单个字符的acsii码值”’
try:
return “%03.d” % ord(char)
except (typeerror, valueerror):
print “key error.”
exit(1)
def __get_ascii2char(self, ascii):
if self.is_ascii_range(ascii):
return chr(ascii)
else:
print “ascii error(%d)” % ascii
exit(1)
def __get_ascii2str(self, n_chars):
ls = []
s = “%s” % n_chars
n, p = pmod(len(s), 3)
if p > 0:
nret = int(s[0 : p])
ls.append( self.__get_ascii2char(nret))
ptmp = p
while ptmp < len(s):
ls.append( self.__get_ascii2char( int(s[ptmp: ptmp + 3])) )
ptmp += 3
return "".join(ls)
#================================================================================
# 工具接口
#================================================================================
def is_number(self, value):
try:
int(value)
return true
except (typeerror, valueerror):
pass
return false
def is_ascii_range(self, n):
return 0