Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a C (\0 terminated) string to a PHP string

PHP is one of those languages I use periodically, but usually have to dust the cobwebs off when I start using it again. The same applies this week whilst I port some C code to PHP. This uses a lot of AES encryption and SHA256 hashing - all working fine so far. However, decrypted strings come out in "C" form - i.e. terminated with a zero byte followed by "garbage" padding bytes.

I currently "trim" these C-style strings to PHP form with the following:

$iv = strpos( $hashsalt8, "\0");
if ($iv)
   $hashsalt8 = substr( $hashsalt8, 0, $iv );

Seems long-winded and that there should be a one line function call instead, but I can't find it?

Note: Although in this case the "hash salt" name implies I might know the length of the original string, this is unknown in the general case. Clearly a one line solution is available using substr() when the length is known a priori.

like image 754
winwaed Avatar asked Dec 12 '22 18:12

winwaed


1 Answers

Use strstr:

$hashsalt8 = strstr($hashsalt8, "\0", TRUE);

An uglier solution for versions less than 5.3.0 (where the third parameter isn't available) uses the strrev, substr and strrchr functions instead:

$hashsalt8 = strrev(substr(strrchr(strrev($hashsalt8), "\0"), 1));
like image 132
You Avatar answered Jan 05 '23 03:01

You