PHP AES encrypt / decrypt(PHP AES 加密/解密)
问题描述
我找到了一个在 PHP 中编码/解码字符串的示例.起初它看起来很好,但它不起作用:-(
I found an example for en/decoding strings in PHP. At first it looks very good but it wont work :-(
有人知道是什么问题吗?
Does anyone know what the problem is?
$Pass = "Passwort";
$Clear = "Klartext";
$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypted: ".$crypted."</br>";
$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypted: ".$newClear."</br>";
function fnEncrypt($sValue, $sSecretKey) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sDecrypted, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function fnDecrypt($sValue, $sSecretKey) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sEncrypted), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
结果是:
加密:boKRNTYYNp7AiOvY1CidqsAn9wX4ufz/D9XrpjAOPk8=
解密:—‚(ÑÁ ^ yË~F'¸®Ó–í œð2Á_B‰—
推荐答案
$sDecrypted
和 $sEncrypted
在您的代码中未定义.查看有效的解决方案(但不安全!):
$sDecrypted
and $sEncrypted
were undefined in your code. See a solution that works (but is not secure!):
这个例子不安全!不要使用它!
<小时>
$Pass = "Passwort";
$Clear = "Klartext";
$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypred: ".$crypted."</br>";
$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypred: ".$newClear."</br>";
function fnEncrypt($sValue, $sSecretKey)
{
return rtrim(
base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$sSecretKey, $sValue,
MCRYPT_MODE_ECB,
mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_256,
MCRYPT_MODE_ECB
),
MCRYPT_RAND)
)
), " "
);
}
function fnDecrypt($sValue, $sSecretKey)
{
return rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
$sSecretKey,
base64_decode($sValue),
MCRYPT_MODE_ECB,
mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_256,
MCRYPT_MODE_ECB
),
MCRYPT_RAND
)
), " "
);
}
但是此代码中存在其他问题使其不安全,尤其是使用 ECB(这不是加密模式,只是加密模式之上的构建块可以定义).请参阅 Fab Sa 的回答 以快速解决最严重的问题和 Scott 的回答如何正确地做到这一点.
But there are other problems in this code which make it insecure, in particular the use of ECB (which is not an encryption mode, only a building block on top of which encryption modes can be defined). See Fab Sa's answer for a quick fix of the worst problems and Scott's answer for how to do this right.
这篇关于PHP AES 加密/解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP AES 加密/解密


- PHP foreach() 与数组中的数组? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01