Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP MD5 equivalent to Java
    text
    copied!<p>I need a PHP equivalent for Java's MD5 functionality which takes a byte array and return the hash as a 16 byte array back. <strong>I'm not need an Java equivalent for the PHP's md5 function.</strong> The problem is that the PHP's <code>md5</code> function takes only strings, not byte arrays.</p> <p>Heres is the expected result in Java:</p> <pre><code>// input byte array // for short: 123456 final byte[] data = new byte[] { (byte) 0x12, (byte) 0x34, (byte) 0x56 }; // expected 16 hash bytes // for short: ae1fa6209a246b8b2f2cd2d21be8f2e1 final byte[] expectedHash = new byte[] { (byte) 0xae, (byte) 0x1f, (byte) 0xa6, (byte) 0x20, (byte) 0x9a, (byte) 0x24, (byte) 0x6b, (byte) 0x8b, (byte) 0x2f, (byte) 0x2c, (byte) 0xd2, (byte) 0xd2, (byte) 0x1b, (byte) 0xe8, (byte) 0xf2, (byte) 0xe1 }; </code></pre> <p>My try in PHP is:</p> <pre><code>&lt;?php // input byte array $data = array(0x12, 0x34, 0x56); // pack data in a string, becouse md5 can only // compute a hash for a string $dataString = pack('C*', $data); // is it the right way? var_dump($dataString); // compute the hash and get a string back $hash = md5($dataString, true); // expected 16 hash bytes // for short: ae1fa6209a246b8b2f2cd2d21be8f2e1 $expected = array( 0xae, 0x1f, 0xa6, 0x20, 0x9a, 0x24, 0x6b, 0x8b, 0x2f, 0x2c, 0xd2, 0xd2, 0x1b, 0xe8, 0xf2, 0xe1); var_dump($expected); // convert the string back to a byte array $actual = unpack('C*', $hash); // is it the right way? var_dump($actual); assert($expected == $actual); ?&gt; </code></pre> <p><code>$dataString</code> has the length of 0. So the first error must be in <code>pack</code>. But I don't know how to pack an arbitrary byte array into a string. Can you give me the right <code>format</code> argument for that?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload