PHP mcrypt_encrypt / mcrypt_decrypt问题,返回一个不同的值 [英] PHP mcrypt_encrypt/mcrypt_decrypt issue, returns a different value

查看:205
本文介绍了PHP mcrypt_encrypt / mcrypt_decrypt问题,返回一个不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找答案,但在这里找不到。请原谅我,如果这个问题已经被问了。

I was looking for an answer but could not find it here. Please excuse me if this question was already asked.

我有一个简单的代码加密和解密一个字符串,字符串看起来一样,但是当使用==比较它们时不一样,所以哈希也不一样..

I have a simple code encrypting and decrypting a string, strings look the same, but when comparing them using == they do not appear to be the same, so hashes are different as well..

这是我的代码:

$oppa = "rompish";
$opp_enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, "key", $oppa, MCRYPT_MODE_ECB);
$opp_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, "key", $opp_enc, MCRYPT_MODE_ECB);

echo $oppa."<br />".$opp_dec."<br />";

if ($oppa == $opp_dec) echo "YAY"; else echo "NOPE";

在页面上:

rompish
rompish
NOPE

rompish rompish NOPE

请告诉我我做错了什么。

Please tell me what I am doing wrong.

谢谢!

推荐答案


AES总是以16个字节的块加密东西。显然
mcrypt_encrypt 用零字节填充字符串,直到它为
倍数为16。 mcrypt_decrypt 尽可能地解密,但缺少
信息来删除填充。而且你愚弄自己
,因为即使 oppa_dec
实际上以9个零字节结尾,所显示的值看起来一样。使用明智的填充方案
代替。 - GregS

AES always encrypts things in blocks of 16 bytes. Apparently mcrypt_encrypt pads the string out with zero bytes until it is a multiple of 16. mcrypt_decrypt dutifully decrypts this but lacks the information to remove the padding. And you are fooling yourself because the displayed values look the same even though oppa_dec actually ends with 9 zero bytes. Use a sensible padding scheme instead. – GregS

删除这些空字符,您可以使用 rtrim 功能。运行解密输出后,应该相等。

To remove these null characters, you can use the rtrim function. After running the decrypted output through that it should be equal.

这篇关于PHP mcrypt_encrypt / mcrypt_decrypt问题,返回一个不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆