我已经创建了这个类(感谢@Sani Huttunen的想法)。它允许每次生成不同的文本,即使对于相同的输入文本也可以成功解码。
class Encoder
{
private static $prefix = '@[email protected]';
public static function php_aes_encrypt($text, $key)
{
if (!trim($text)) {
return '';
}
$iv = self::generateRandomString();
$key = self::mysql_aes_key($key);
$pad_value = 16 - (strlen($text) % 16);
$text = str_pad($text, (16 * (floor(strlen($text)/16) + 1)), chr($pad_value));
$ciphertext = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$key,
$text,
MCRYPT_MODE_CBC,
$iv
);
$ciphertext = self::getPrefix() . base64_encode($ciphertext . $iv);
return $ciphertext;
}
public static function php_aes_decrypt($text, $key)
{
$text = str_replace(self::getPrefix(), '', $text);
$text = base64_decode($text);
if (!trim($text)) {
return '';
}
$iv = substr($text, -16);
$text = str_replace($iv, '', $text);
$key = self::mysql_aes_key($key);
$text = mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
$key,
$text,
MCRYPT_MODE_CBC,
$iv
);
return rtrim($text, "\0..\16");
}
private static function mysql_aes_key($key)
{
$new_key = str_repeat(chr(0), 16);
for ($i = 0, $len = strlen($key); $i < $len; $i ++) {
$new_key[$i % 16] = $new_key[$i % 16]^$key[$i];
}
return $new_key;
}
private static function getPrefix()
{
return base64_encode(self::$prefix);
}
public static function isEncrypted($ciphertext)
{
$isEncrypted = (false !== strpos($ciphertext, self::getPrefix()));
return $isEncrypted;
}
private static function generateRandomString()
{
return substr(sha1(rand()), 0, 16);
}
}
用法:
$encrypted = Encoder::php_aes_encrypt('my test string', 'key');
echo $encrypted . '<br>';
echo Encoder::php_aes_decrypt($encrypted, 'key');
什么散列如果你能再次扭转到原来的状态 – Ghost 2014-09-29 13:39:45
你混淆了'hash'算法'encryption'算法的点。 'MD5'和'SHA1'是'单向哈希'算法,并不意味着被“解密”。你应该使用'3DES','AES','TwoFish'等加密算法。 – 2014-09-29 13:40:25
'md5'和'sha1'都不是***加密函数,它们是散列算法,它们的重点在于它们只是单向的。好的哈希不能被“解密”_ – 2014-09-29 13:40:57