Home > php教程 > php手册 > php加密算法之实现可逆加密算法和解密分享

php加密算法之实现可逆加密算法和解密分享

WBOY
Release: 2016-06-13 09:44:34
Original
1143 people have browsed it

加密算法如下:

复制代码 代码如下:


function encrypt($data, $key)
{
 $key = md5($key);
    $x  = 0;
    $len = strlen($data);
    $l  = strlen($key);
    for ($i = 0; $i     {
        if ($x == $l)
        {
         $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i     {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}

解密算法如下:

复制代码 代码如下:


function decrypt($data, $key)
{
 $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    for ($i = 0; $i     {
        if ($x == $l)
        {
         $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i     {
        if (ord(substr($data, $i, 1))         {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }
        else
        {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}

上述加密解密的过程均需要用到一个加密密钥(即参数$key)。

复制代码 代码如下:


$data = 'PHP加密解密算法';  // 被加密信息
$key = '123';     // 密钥
$encrypt = encrypt($data, $key);
$decrypt = decrypt($encrypt, $key);
echo $encrypt, "\n", $decrypt;

上述将输出类似如下结果:

复制代码 代码如下:


gniCSOzZG+HnS9zcFea7SefNGhXF
PHP加密解密算法

从上述结果可以看出,这是一组可逆的加密解密算法,可以用于部分需要还原的数据加密。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template