#PHP版对称加密,python重写的
#对称加密解密
def encrypt(data, key):
str = base64.b64encode(data.encode(encoding='utf-8'))
strArr = list(str.decode('utf-8'))
strCount = len(strArr)
for k,v in enumerate(key):
if k<strCount:
strArr[k] = strArr[k] + v
return ''.join(strArr).replace('=','O0O0O').replace('+','o000o').replace('/','oo00o')
def decrypt(data, key):
str = data.replace('O0O0O','=').replace('o000o','+').replace('oo00o','/')
strArr = re.findall(r'.{2}', str)
strCount = len(strArr)
for k,v in enumerate(key):
if k<=strCount and strArr[k] is not None and strArr[k][1] == v:
strArr[k] = strArr[k][0]
return base64.b64decode(''.join(strArr)).decode('utf-8')
class Symmetry
{
/**
* 简单对称加密算法之加密
* @param String $string 需要加密的字串
* @param String $skey 加密EKY
* @return String
*/
public static function encode($string = '', $skey = 'cxphp')
{
//先使用 MIME base64 对数据进行编码后的字符串转换为数组
$strArr = str_split(base64_encode($string));
//计算数组中单元数目
$strCount = count($strArr);
//拼接上加密KEY
foreach (str_split($skey) as $key => $value) {
$key < $strCount && $strArr[$key] .= $value;
}
//替换字符返回加密字符串
return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
* 简单对称加密算法之解密
* @param String $string 需要解密的字串
* @param String $skey 解密KEY
* @return String
*/
public static function decode($string = '', $skey = 'cxphp')
{
//反替换字符串,在变为数组
$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value) {
$key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
}
return base64_decode(join('', $strArr));
}
}