Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

php - Why is mcrypt_encrypt() putting binary characters at the end of my string?

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

<?

$encryptionkey = 'h8y2p9d1';

$card_nbr = "1234";
echo "original card_nbr: $card_nbr <br>
";

$card_nbr_encrypted=encrypt_data($card_nbr);
echo "card_nbr_encrypted: $card_nbr_encrypted <br>
";

$card_nbr_decrypted=decrypt_data($card_nbr_encrypted);
echo "card_nbr_decrypted: $card_nbr_decrypted <br>
";

$len=strlen($card_nbr_decrypted);
echo "length: $len <br>
";



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$<§G3-??-éù3Y2ê×rz¨V?
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?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...