H
H
Hakhagmon2016-03-21 12:43:27
PHP
Hakhagmon, 2016-03-21 12:43:27

Why do php and java get different md5?

There is a java application that generates md5.

public class start {
   
    public static void main (String[] args) throws java.io.UnsupportedEncodingException, java.security.NoSuchAlgorithmException {
      java.io.PrintStream sysout = new java.io.PrintStream(System.out, true, "UTF-8");
 
      String utf8_string = "¤3¤119829406¤2";
      sysout.println(utf8_string);
 
      java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
      byte[] md5_byte_array = md5.digest(utf8_string.getBytes());
 
      java.math.BigInteger md5_biginteger = new java.math.BigInteger(1, md5_byte_array);
      sysout.println(md5_biginteger.toString(16));
    }
  }

as a result, we get 808b085b44dfa7d1ba351f2f33a608de
, but if we use the standard md5 function in php, then md5 is different.
<?
print_r(iconv('WINDOWS-1251', 'UTF-8', md5("¤3¤119829406¤2")));

print_r(md5("¤3¤119829406¤2"));
?>

in both cases we get - fcee312dd5fbbfbfb81e0e92d2ab0af6
I assume that the problem is in the encoding, and something else needs to be added to the php script.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Evgeny Bykov, 2016-03-22
@Hakhagmon

Here: utf8_string.getBytes() is not explicitly set to UTF-8 encoding, so the platform default encoding is used. If you want the PHP script to give the same amount as java, set the encoding corresponding to your platform in it, in your case it is "ISO-8859-1"

M
MamOn, 2016-03-22
@MamOn

Here it works as expected: ideone.com/kg3ktQ
And all because the system encoding is UTF-8. The problem is precisely in the call to the String.getBytes() method, as indicated earlier. But, if the code cannot be changed, then you can run the application in a different system encoding by passing the -Dfile.encoding=UTF-8 parameter to the java launch command line. For example:
java -Dfile.encoding=UTF-8 -jar ваша_программа.jar

D
Dimonchik, 2016-03-21
@dimonchik2013

correctly guess
see how it's done in Python - no encodings:
https://docs.python.org/3/library/hashlib.html

M
Mikhail Osher, 2016-03-21
@miraage

Checked a bunch of md5 online services.
Everywhere issues fcee312dd5fbbfbfb81e0e92d2ab0af6.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question