mcrypt_decrypt PHP proper usage

做~自己de王妃 提交于 2019-12-01 09:57:17

You are close, there are 2 small problems.

First, AES-128 is not a valid cipher constant from mcrypt. AES is really rijndael which you have support for. The mcrypt cipher constant for AES-128 is MCRYPT_RIJNDAEL_128 which is the string rijndael-128. Second, the mcrypt mode must be lowercase.

Changing your code to:

<?php
$retval = mcrypt_decrypt( "rijndael-128",
    base64_decode( "aXJhbmRvbXNlY3VyZWtleQ=="), 
    base64_decode( "3l6xiNdgRG+PkBw5M0lawvJ/fmuTZPRhEcbtqAmOpDI") ,
    "ecb");

echo $retval;

yields the correct output of: Is 3 random enough?

Personally, I'd go with the mcrypt constants rather than the actual strings, so replace rijndael-128 with MCRYPT_RIJNDAEL_128 and ecb with MCRYPT_MODE_ECB.

On a side note, consider using CBC with an IV instead of ECB if you are encrypting lots of sensitive information.

Mcrypt can easily create IVs for you with the proper lengths. Sample code:

$ivsize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv     = mcrypt_create_iv($ivsize);

Use this IV when encrypting and decrypting. You can pass the IV along with your data as a base64 encoded string for portability.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!