PHP可逆加密演算法
阿新 • • 發佈:2019-02-17
AES加密
加密
function zAES_encrypt($str, $privateKey = "1234567812345678", $iv = "1234567812345678") {
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $str, MCRYPT_MODE_CBC, $iv);
return base64_encode($encrypted);
}
注:$iv 的長度根據 mcrypt_encrypt 方法中的第一個引數和第四個引數決定
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
解密
function zAES_decrypt($str, $privateKey = "1234567812345678", $iv = "1234567812345678") {
$encryptedData = base64_decode($str);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);
}
偽AES加密
加密
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);
}
解密
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;
}