PHP可逆加密解密算法

WBOY
Release: 2016-06-20 13:03:23
Original
878 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);
}
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;
}
Copy after login

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

$data = &#39;PHP加密解密算法&#39;; // 被加密信息 

$key = &#39;123&#39;; // 密钥 

$encrypt = encrypt($data, $key); 

$decrypt = decrypt($encrypt, $key); 

echo $encrypt, "\n", 

$decrypt;
Copy after login

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

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!