Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's MessageDigest SHA1-algorithm returns different result than SHA1-function of php

Tags:

java

php

sha1

I have a SQL table with usernames and passwords. The passwords are encoded using MessageDigest's digest() method. If I encode a password - let's say "abcdef12" - with MessageDigest's digest() method and then convert it to hexadecimal values, the String is different than if I do the same using PHP's SHA1-method. I'd expect these values to be exactly the same though.

Code that is used to encode the passwords:

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] passbyte;
passbyte = "abcdef12".getBytes("UTF-8");
passbyte = md.digest(passbyte);

The conversion of the String to hexadecimal is done using this method:

public static String convertStringToHex(String str) {

    char[] chars = str.toCharArray();

    StringBuffer hex = new StringBuffer();
    for (int i = 0; i < chars.length; i++) {
        hex.append(Integer.toHexString((int) chars[i]));
    }

    return hex.toString();
}

Password: abcdef12

Here's the password as returned by a lot of SHA1-hash online generators and PHP SHA1()-function: d253e3bd69ce1e7ce6074345fd5faa1a3c2e89ef

Here's the password as encoded by MessageDigest: d253e3bd69ce1e7ce674345fd5faa1a3c2e2030ef

Am I forgetting something?

Igor.

Edit: I've found someone with a similar problem: C# SHA-1 vs. PHP SHA-1...Different Results? . The solution was to change encodings.. but I can't change encodings on the server-side since the passwords in that SQL-table are not created by my application. I use client-side SHA1-encoding using a JavaScript SHA1-class (more precisely: a Google Web Toolkit-class). It works and encodes the string as expected, but apparently using ASCII characters?..

like image 627
Igor Avatar asked Sep 30 '11 01:09

Igor


People also ask

Is SHA1 deprecated?

NIST formally deprecated use of SHA-1 in 2011 and disallowed its use for digital signatures in 2013.

Is SHA1 still used?

Browsers stopped supporting SHA-1 in recent years and public entities no longer issue them. However, as my recent engagements have shown, there are many other non-browser use cases for these certificates that companies still rely on.

What is the length of SHA1 hash?

The hash size for the SHA1 algorithm is 160 bits.

Is MessageDigest thread safe?

MessageDigest is not thread-safe, and in general, you should use every new instance for every thread.


1 Answers

Try this - it is working for me:

MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
    sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();

Regards, Konki

like image 181
Konki Avatar answered Nov 15 '22 15:11

Konki