1

I am trying to connect up a Java application with a web application (in PHP), where a person can register a user on either the Java application, or on the web application. I'm trying to find the equivalent of the PHP "hash" function in Java.

For creating the hash in the web app, this is the code I use:

$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));

$password = hash('sha256', $_POST['password'] . $salt);

for($round = 0; $round < 65536; $round++) {
    $password = hash('sha256', $password . $salt);
}

The encrypted password and salt get stored in their own columns with the user, a little bit like this:

|=====|==========|============|==========|
| ID  | Username |  Password  |   Salt   |
| 1   | Bob      | x24da0el.. | 39bbc9.. |
|=====|==========|============|==========|

I've tried everything and I can't get find the same method in Java.

1 Answer 1

4

Yes, take a look at the MessageDigest class of Java: http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html

It provides 3 hashing algorithms:
-MD5
-SHA-1
-SHA-256

Example for hashing a file:

MessageDigest md = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream("~/Documents/Path/To/File.txt");

byte[] dataBytes = new byte[1024];

int nread = 0; 
while ((nread = fis.read(dataBytes)) != -1) {
  md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();

//Convert "mdbytes" to hex String:
StringBuffer hexString = new StringBuffer();
for (int i=0;i<mdbytes.length;i++) {
  hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
}

return hexString.toString();

Here is the example for hashing a String:

String password = "123456";

MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());

byte byteData[] = md.digest();

//Convert "byteData" to hex String:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
    sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}

return sb.toString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.