如何在PHP中解密以NUL字符结尾的二进制数据? [英] How can I decrypt binary data that ended with NUL characters in PHP?

查看:215
本文介绍了如何在PHP中解密以NUL字符结尾的二进制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

$data = "Test Data\x00\x00";
echo strlen($data);

$key = "mykey";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, MD5($key, true), $data, MCRYPT_MODE_ECB);
echo strlen($encrypted);

$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, MD5($key, true), $encrypted, MCRYPT_MODE_ECB);
echo strlen($decrypted);

$newData = rtrim($decrypted,"\x00");
echo strlen($newData);

输出:

11
16
16
9  <-- I want 11 here

所以,有没有办法解密在加密之前可能已被零填充的数据,并获取正确的长度数据?

So, is there any way to decrypt data that may already be null-padded before encryption, and get the correct length data back?

推荐答案

发生这种情况是因为加密时,数据需要一定的大小。您的数据小于该数据,因此它被填充。 PHP填充NULL字符的数据,所以当您 rtrim 时,您将删除您的NULL和添加了PHP的

This is happening because when encrypting, the data needs to be a certain size. Your data is smaller than that, so it's being padded. PHP pads data with NULL characters, so when you rtrim, you're removing both your NULLs and the ones added with PHP.

一种解决方案是使用其他方法将数据填充到正确的长度。我个人使用 PKCS7填充

One solution is to pad the data to the correct length by using another method. I personally use PKCS7 padding.

以下是使用此填充方法的示例(从 https://gist.github。 com / 1077723 ):

Here's an example of how to use this padding method (adapted from https://gist.github.com/1077723):

$data = "Test Data\x00\x00";

$key = "mykey";

$blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);

// PKCS7 Padding
$pad = $blocksize - (strlen($data) % $blocksize);
$data .= str_repeat(chr($pad), $pad);

$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, MD5($key, true), $data, MCRYPT_MODE_ECB);

$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, MD5($key, true), $encrypted, MCRYPT_MODE_ECB);

// PKCS7 Padding
$strPad = ord($decrypted[strlen($decrypted)-1]);
$newData = substr($decrypted, 0, -$strPad);

演示: http://ideone.com/bMZxyf

这篇关于如何在PHP中解密以NUL字符结尾的二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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