java mcrypt encrypt,为什么mcrypt_encrypt()将二进制字符放在字符串的末尾?

Here is a PHP demo script that encrypts and decrypts data:

$encryptionkey = 'h8y2p9d1';

$card_nbr = "1234";

echo "original card_nbr: $card_nbr
\n";

$card_nbr_encrypted=encrypt_data($card_nbr);

echo "card_nbr_encrypted: $card_nbr_encrypted
\n";

$card_nbr_decrypted=decrypt_data($card_nbr_encrypted);

echo "card_nbr_decrypted: $card_nbr_decrypted
\n";

$len=strlen($card_nbr_decrypted);

echo "length: $len
\n";

function encrypt_data($text){

global $encryptionkey;

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);

$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $encryptionkey, $text, MCRYPT_MODE_ECB, $iv);

return $encrypted_text;

}

function decrypt_data($text){

global $encryptionkey;

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);

$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $encryptionkey, $text, MCRYPT_MODE_ECB, $iv);

return $decrypted_text;

}

?>

The output is:

original card_nbr: 1234

card_nbr_encrypted: vY¨(Z$

card_nbr_decrypted: 1234 (and 28 binary characters)

length: 32

The output is successfully decrypted, but 28 binary characters are added to the end. This can most easily be seen in Firefox, when viewing HTML source.

The string length of 32 also demonstrates this. Any ideas?

qsLZP.png

解决方案

The returned string is padded out to fill n * blocksize bytes using the null character \0 so that is why you are seeing the extra data.

If you run $card_nbr_decrypted= rtrim($card_nbr_decrypted, "\0"); it should return the actual data.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值