Converting C string (\ 0 completed) to PHP string

PHP is one of those languages ​​that I use periodically, but you usually have to vacuum the web when I start using it again. The same applies this week while I am porting some C code to PHP. This uses a lot of AES encryption and SHA256 hashing - everything works fine. However, the decrypted lines come in the form of "C", that is, end with a zero byte, followed by the filling bytes of the "garbage".

I am currently "trimming" these C-style lines in PHP form with the following:

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

It seems to be long and that there should be a single line call instead, but I can't find it?

Note. Although the name "hash salt" in this case means that I could know the length of the original string, this is not known in the general case. Clearly, a single-line solution is available using substr() when the length is known a priori.

+4
source share
3 answers

Use strstr :

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

The carbon solution for versions less than 5.3.0 (where the third parameter is not available) uses strrev , substr and strrchr :

 $hashsalt8 = strrev(substr(strrchr(strrev($hashsalt8), "\0"), 1)); 
+9
source

Should there be no more than 32 bytes of padding? (from your comment here)

You might be able to do something like this:

 preg_replace('/\x00.{0,32}$/', "", $hashsalt8); 

Pay attention to single quotes instead of doubles, if you use double quotes that \x00 seem to break the preg :)

+2
source

The strtok will do this in one pass instead of two:

$hashsalt8 = strtok($hashsalt8, "\0");

Since PHP 4.1.0, however, strtok will not return an empty string if the input string starts with a zero byte. To handle this case, you can do the following:

  if ($ hashsalt8 [0] == "\ 0") {
   $ hashsalt8 = '';
 }
 else {
   $ hashsalt8 = strtok ($ hashsalt8, "\ 0");
 }

Note that an input line starting with a zero byte also throws an error in your current code. In this case, strpos will return 0 and if ($iv) will fail.

You must use the !== operator to distinguish between 0 and false :

  $ iv = strpos ($ hashsalt8, "\ 0");
 if ($ iv! == false) {
    $ hashsalt8 = substr ($ hashsalt8, 0, $ iv);
 }
+2
source

All Articles