1

Possible Duplicate:
Java’s MessageDigest SHA1-algorithm returns different result than SHA1-function of php

what I use:

java:

public String sha1(String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

result:

java: System.out.println(sha1("foobar123dsadn23u1wdqqwdyxdasd"));
php:                echo sha1('foobar123dsadn23u1wdqqwdyxdasd');

php:  d8033103e9aaf67af13a4b45534b2d0f6d8dfded
java: d83313e9aaf67af13a4b45534b2df6d8dfded

Why not the same the two hash?

Community
  • 1
  • 1
Gergely Fehérvári
  • 7,811
  • 6
  • 47
  • 74

1 Answers1

8

That is because Integer.toHexString in Java does not print two digits if the number is less than 16. So, for example 8 becomes 8 instead of 08.

You need to propertly format the numbers. This should do it:

hexString.append(String.format("%02X", 0xFF & messageDigest[i]));
Jesper
  • 202,709
  • 46
  • 318
  • 350