Home > php教程 > php手册 > 一组PHP可逆加密解密算法

一组PHP可逆加密解密算法

WBOY
Release: 2016-06-13 09:43:51
Original
1261 people have browsed it

对于大部分密码加密,我们可以采用md5、sha1等方法。可以有效防止数据泄露,但是这些方法仅适用于无需还原的数据加密。

对于需要还原的信息,则需要采用可逆的加密解密算法。

下面一组PHP函数是实现此加密解密的方法:

加密算法如下:

function encrypt($data, $key)
{
	$key	=	md5($key);
    $x		=	0;
    $len	=	strlen($data);
    $l		=	strlen($key);
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l) 
        {
        	$x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}<br /><br /><span>解密算法如下:</span>
Copy after login
function decrypt($data, $key)
{
	$key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l) 
        {
        	$x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $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;
}<br /><br /><span>上述加密解密的过程均需要用到一个加密密钥(即参数$key)。</span><br /><br />
Copy after login
$data = 'PHP加密解密算法';		// 被加密信息
$key = '123';					// 密钥
$encrypt = encrypt($data, $key);
$decrypt = decrypt($encrypt, $key);
echo $encrypt, "\n", $decrypt;<br /><br /><br />
Copy after login

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

gniCSOzZG+HnS9zcFea7SefNGhXF
PHP加密解密算法

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

<br /><br />
Copy after login
Copy after login
<br /><br />
Copy after login
Copy after login
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