Hash returns different results for the same input

areuz :

I can't get MessageDigest to output the same hash even using the same string 3 times in a row. I've simplified the code to the basics and this behaviour still persists.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

public class foo {

    private static byte[] hashPass(String _pass) {  
        MessageDigest mDigest;
        try {
            mDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("[" + e.getMessage() + "] Unable to create message digest");
            return null;
        }

        try {
            return mDigest.digest( _pass.getBytes("UTF-8") );
        } catch (UnsupportedEncodingException e) {
            System.out.println("[" + e.getMessage() + "]");
            return null;
        }
    } //private boolean hashPass(...)

    public static void main(String[] args) {

        System.out.println("Hash1: " + hashPass("string"));
        System.out.println("Hash2: " + hashPass("string"));     
        System.out.println("Hash3: " + hashPass("string"));     
    }

}

//Outputs:
//Hash1: [B@7852e922
//Hash2: [B@4e25154f
//Hash3: [B@70dea4e

The strange thing is that it outputs the same outputs on every rerun - this implies that the internal state changes every time in the same way? Does it use salt or other inputs that I'm not aware of and should specify/use?

Karol Dowbecki :

hashPass() method returns a byte[] array and in java arrays don't have a meaningful toString() representation. To display the elements of the array use Arrays.toString():

System.out.println(Arrays.toString(hashPass("string")));

which will print:

[71, 50, -121, -8, 41, -115, -70, 113, 99, -88, -105, -112, -119, 88, -9, -64, -22, -25, 51, -30, 93, 46, 2, 121, -110, -22, 46, -36, -101, -19, 47, -88]

or convert the byte[] array to hex representation:

byte[] bytes = hashPass("string");
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
    sb.append(String.format("%02X", b));
}
System.out.println(sb);

which will print:

473287F8298DBA7163A897908958F7C0EAE733E25D2E027992EA2EDC9BED2FA8

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159634&siteId=1