Chris
Chris

Reputation: 4728

Converting MD5Bytes and getBytes Java code to PHP

I have been given this sample java code that I need to convert into PHP

JAVA

String rawStr = logistics_interface + signKey;
String data_digest = new String(Base64.encodeBase64(MD5Bytes(rawStr.getBytes("utf-8"))), "utf-8");

I have been using this PHP:

$rawStr = $logistics_interface . $signKey;
$data_digest = base64_encode(md5(utf8_encode($rawStr)));

Using these test values:

$logistics_interface = '<order>helloworld</order>';
$signKey = '123';

My PHP code gives:

ZWUwNGZmMWU2MTQ1NGRmOTcwN2U2ZmY3MmNlMjlkOTk=

But I am being told by the API supplier that the correct value of $data_digest should be:

7gT/HmFFTflwfm/3LOKdmQ==

Upvotes: 1

Views: 2024

Answers (1)

tkausl
tkausl

Reputation: 14269

In Java, MD5Bytes returns the plain bytes of the MD5 result, in PHP the md5 function returns a human-readable hex-representation of the bytes, hence to get the exact same result you get in Java you need to undo the binary-to-hex conversion first with hex2bin

$data_digest = base64_encode(hex2bin(md5($rawStr)));

should give you the exact same result: Example

Upvotes: 2

Related Questions