自定义对称 加密和解密

IT-Pony 2016-06-24 PM 1597℃ 0条

自定义

<?php

    function selfEncode($str, $k) {
        $encoded = '';
        $len = strlen($str);
        $lk = strlen($k);
        for($i = 0; $i < $len; $i++) 
        {
            $mod = fmod($i, $lk);
            $encoded .= $str[$i. ''] ^ $k[$mod.''];
        }
        $encoded = base64_encode($encoded);
 
        return $encoded;
    }
    function selfDecode($str, $k) {
        $str = base64_decode($str);
        $decoded = '';
        $len = strlen($str);
        $lk = strlen($k);
        for($i = 0; $i < $len; $i++) 
        {
            $mod = fmod($i, $lk);
            $decoded .= $str[$i. ''] ^ $k[$mod.''];
        }
 
        return $decoded;
    }

复制可用

// 加密数据并写到cookie里
$cookie_data = $this -> encrypt("nowamagic", $data);
              
$cookie = array(
    'name'   => '$data',
    'value'  => $cookie_data,
    'expire' => $user_expire,
    'domain' => '',
    'path'   => '/',
    'prefix' => ''
);
$this->input->set_cookie($cookie);

// 加密
public function encrypt($key, $plain_text) {  
    $plain_text = trim($plain_text);  
    $iv = substr(md5($key), 0,mcrypt_get_iv_size                 (MCRYPT_CAST_256,MCRYPT_MODE_CFB));  
    $c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);  
    return trim(chop(base64_encode($c_t)));  
}  

使用的时候再解密:
if( isset($_COOKIE['data']) )
{
    //用cookie给session赋值
    $_SESSION['data'] = decrypt("nowamagic", $_COOKIE['data']);
}

function decrypt($key, $c_t) {  
    $c_t = trim(chop(base64_decode($c_t)));  
    $iv = substr(md5($key), 0,mcrypt_get_iv_size     (MCRYPT_CAST_256,MCRYPT_MODE_CFB));  
    $p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);  
    return trim(chop($p_t));  
}
标签: none

非特殊说明,本博所有文章均为博主原创。

评论啦~