1

I used the function below to calculate a hash of password. My problem is when I try to print hashcode I get an array of int even that the hash variable is of type String.

private static String getHashCode(String password) {
    String hash = "";
    try {
        MessageDigest md5 = MessageDigest.getInstance("SHA-512");
        byte [] digest = md5.digest(password.getBytes("UTF-8"));
        hash = Arrays.toString(digest);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    System.out.println(hash);
    return hash;
}
1
  • I think you are getting a String in which all entries of your array are printed. Maybe you want a hex ouput of your byte array? Commented Mar 5, 2014 at 14:16

3 Answers 3

2

This is normal. You are calling:

hash = Arrays.toString(digest);

So you get a string which represents the array digest in a string form.

Sign up to request clarification or add additional context in comments.

Comments

1

That is because you called Arrays.toString which returns a direct string representation of the array.

Instead, you probably want a hexadecimal representation of the byte[] array, which you can do with something like this (untested):

StringBuilder hexString = new StringBuilder();
for (int i = 0; i < digest.length; i++) {
    String hex = Integer.toHexString(0xFF & digest[i]);
    if (hex.length() == 1) {
        hexString.append('0');
    }
    hexString.append(hex);
}
String hash = hexString.toString();

1 Comment

I didn't know that. So I will do like you said. Thanks
1

As you see byte [] digest is a byte array that contain int values after that you transform to string so confert array of int into string so it's normal....

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.