json_decode在已通过加密的字符串上返回NULL [英] json_decode returns NULL on string that has passed through encryption
问题描述
mcrypt
函数来加密和解密任何文本,在这里是: 函数加密($ key,$ data){
$ encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192,$ key, $ data,MCRYPT_ENCRYPT);
返回base64_encode($ encrypted_data);
}
函数解密($ key,$ encryptedData){
$ decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192,$ key,base64_decode($ encryptedData),MCRYPT_DECRYPT);
return $ decrypt;
}
我有一个有效的JSON字符串,我已经测试了 json_decode
而不通过加密,它可以工作。但是当我加密然后解密它,然后尝试 json_decode
它只返回 NULL
。 / p>
现在我只是在一个简单的脚本中调试它,它是:
包括( coreFunctions.php);
$ arr ='{number:4646464646,type:home}';
$ key =ladida;
$ locked = encrypt($ key,$ arr);
var_dump($ locked);
var_dump(json_decode(decrypt($ key,$ locked),true));
我有验证 / code>是 SAME 。
任何人都可以告诉我为什么会发生这种情况?
更新
我发现前后的 strlen()
是不同的。那么我如何确保在整个加密过程中保持不变,或者在完成之后修复它?
bin2hex读取:
033303539222c2274797065223a22686f6d65227d00000000000000000000
这意味着您在解密的字符串中具有尾随NUL个字节。这是因为 mcrybt_cbc
以块方式运行。它将填充输入和输出到16(或24)个字节的倍数。 (输出有时甚至可能包含垃圾;因此长度字段通常会占用大多数加密方案/容器格式。)
在您的答案中,您可以避免使用 rtrim
解密后。或更准确地说:
json_decode(rtrim(decrypt($ key,$ locked),\0),true) ;
I am trying to secure information on my database and the standard type of data is JSON and I just wrote some simple mcrypt
functions that encrypt and decrypt any text, here they are:
function encrypt($key, $data){
$encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT);
return base64_encode($encrypted_data);
}
function decrypt($key, $encryptedData){
$decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, base64_decode($encryptedData), MCRYPT_DECRYPT);
return $decrypt;
}
I have a valid JSON string and I've tested the json_decode
without passing through encryption, and it works. But when I encrypt then decrypt it then try to json_decode
it only returns NULL
.
Right now I'm just debugging it in a simple script here it is:
include("coreFunctions.php");
$arr = '{"number":"4646464646","type":"home"}';
$key = "ladida";
$locked = encrypt($key, $arr);
var_dump($locked);
var_dump(json_decode(decrypt($key, $locked), true));
I have verified the output of decrypt
is a the SAME as it went in.
Can anyone tell me why this is happening?
UPDATE
I've discovered the strlen()
before and after is different. So how can I either make sure that it stays the same throughout the encryption process or fix it after it's done?
bin2hex reads:
033303539222c2274797065223a22686f6d65227d00000000000000000000
That means you have trailing NUL bytes in the decrypted string. This happens because the mcrybt_cbc
operates block-wise. It'll fill up input and output to multiples of 16 (or 24) bytes to do so. (The output might sometimes even contain garbage; hencewhy a length field often occampanies most encryption schemes / container formats.)
In your ase you can get away with applying rtrim
after the decryption. Or more exactly:
json_decode(rtrim(decrypt($key, $locked), "\0"), true);
这篇关于json_decode在已通过加密的字符串上返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!