0

I am currently trying to get Java to generate the same hash for a string as PHP's hash algorithm does.

I have come close enough:

hash('sha512', 'password');

outputs:

b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86

Java code:

public static void main(String[] args) {
    hash("password");
}

private static String hash(String salted) {
    byte[] digest;
    try {
        MessageDigest mda = MessageDigest.getInstance("SHA-512");
        digest = mda.digest(salted.getBytes("UTF-8"));
    } catch (Exception e) {
        digest = new byte[]{};
    }

    String str = "";
    for (byte aDigest : digest) {
        str += String.format("%02x", 0xFF & aDigest);
    }

    return str;
}

This outputs the same.

My problem is when I use the third argument within PHP's hash function. On PHP's site it's described as following:

raw_output
    When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

I am not quite sure how to implement this extra parameter. I think mainly my question would be, how do I convert a String object into a binary String object? Currently, running it with PHP generates the following: http://sandbox.onlinephpfunctions.com/code/a1bd9b399b3ac0c4db611fe748998f18738d19e3

Hosh Sadiq
  • 1,416
  • 2
  • 20
  • 41
  • Have a look [here][1]. Hope that helps. [1]: http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – user3622622 Jun 08 '14 at 00:28
  • What do you intend to do with the raw binary data? And just use a HexDecoder (or use the byte[] digest you already have)... – Elliott Frisch Jun 08 '14 at 00:37
  • @user3622622 I will have a look – Hosh Sadiq Jun 08 '14 at 01:04
  • @ElliottFrisch This is how Symfony2's FOSUserBundle implements generating the password hash (plus some other bit of logic, but the rest is fairly simple). After generating the hash like this, FOSUserBundle encodes the hash as base64 and saves this base64 encoded string in the database. I need to be able to do this from Java. So that a user can be created through Java and you would still be able to login. – Hosh Sadiq Jun 08 '14 at 01:05
  • @user3622622 unfortunately that's not the same issue as mine. The question is about a string representation of the binary of an integer (crazy sentence). Where as I just want the binary representation of a character. – Hosh Sadiq Jun 08 '14 at 22:38

1 Answers1

0

This should reproduce the outcome from your link:

String strBinary = null;
try {
    strBinary = new String(digest, "UTF-8");
} catch (UnsupportedEncodingException e) {
}

and you'll need these imports at the top of your file:

import java.nio.charset.Charset;
import java.io.UnsupportedEncodingException;

I hope I understood your issue correctly.

user3622622
  • 107
  • 1
  • 8