如何在php中加密和解密数据?
到目前为止,我的代码是:-
function encrypter($plaintext)
{
$plaintext = strtolower($plaintext);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$plaintext,MCRYPT_MODE_ECB);
return trim(base64_encode($crypttext));
}
function decrypter($crypttext)
{
$crypttext = base64_decode($crypttext);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);
return trim($crypttext);
}
$test = "abc@gmail.com";
回显加密器(测试);
输出为
iLmUJHKPjPmA9vY0jfQ51qGpLPWC/5bTYWFDOj7Hr08=
回显解密器(测试);
输出为
��-
在 decrypter()
函数中,返回了错误的数据。
您应该返回$plaintext
而不是$crypttext
:
function decrypter($crypttext)
{
$crypttext = base64_decode($crypttext);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);
//return trim($crypttext);
return trim($plaintext);
}
此页面上的其他代码示例(包括问题)不安全。
为了安全起见:
- 不要使用 mcrypt。
- 使用经过身份验证的加密。
- 切勿使用 ECB 模式(又名
MCRYPT_MODE_ECB
)。
有关 PHP 中的安全加密,请参阅此答案。
这是我
使用的。超级简单。
function encrypt_decrypt($action, $string) {
$output = false;
$key = '$b@bl2I@?%%4K*mC6r273~8l3|6@>D';
$iv = md5(md5($key));
if( $action == 'encrypt' ) {
$output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
$output = rtrim($output, "");
}
return $output;
}
您可以将$key
更改为所需的任何内容,也可以将其保留。(顺便说一句,这不是我的钥匙)
encrypt_decrypt('encrypt', $str)
加密
解密encrypt_decrypt('decrypt', $str)
在解密器函数中,更改
return trim($crypttext);
自
return trim($plaintext);
但是看看你的函数,我不太确定它是否会返回完全相同的字符串,因为 strtolower 函数。你不能只做一个 strtoupper 函数,因为原始文本可能不全是大写字母。
警告 mcrypt_encrypt 已从 PHP 7.1.0 开始弃用。强烈建议不要依赖此功能。请改用openssl_encrypt。