1

I'm converting some C# to Java. The C# is:

// Return a SHA256 hash of a string, formatted in hex
private static string HashPassword(string password)
{
    SHA256Managed hash = new SHA256Managed();
    byte[] utf8 = UTF8Encoding.UTF8.GetBytes(password);
    return BytesToHex(hash.ComputeHash(utf8));
}

In Java I replaced SHA256Managed with MessageDigest:

private static String HashPassword(String password)
{
    MessageDigest hash = MessageDigest.getInstance("SHA-256");
    byte[] utf8 = hash.digest(password.getBytes(StandardCharsets.UTF_8));

    return BytesToHex(hash.ComputeHash(utf8)); // ComputeHash?
}

but MessageDigest does not have ComputeHash() nor do I see its equivalent. Is MessageDigest the correct class to use here? If so, what do I do for ComputeHash(). If not what class do I use?

Note that BytesToHex Converts a byte array to a hex string.

2
  • 2
    Did you read the Javadoc for MessageDigest? The method to finalize the hash is digest() for a hash calculated in several segments, or digest(byte[]) for a single-segment calculation (or as the final segment of a multi-segment hash). Commented Dec 14, 2016 at 20:20
  • I did read, but not carefully. My mistake. Commented Dec 15, 2016 at 14:15

2 Answers 2

4

MessageDigest is stateful. You pass data to it incrementally, and call digest() to compute the hash over all the data when you're done.

The hash.digest(byte[]) method you're calling is essentially a shorthand for hash.update(byte[]) then hash.digest().

Calling digest() also resets the MessageDigest instance to its initial state.

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

Comments

2

In your Java, the variable utf8 contains your computed hash unlike the C#. To match the way the C# looks it should be:

byte[] utf8 = password.getBytes(StandardCharsets.UTF_8);

return bytesToHex(hash.digest(utf8));

Side note: Please respect Java coding standards with respect to lowerCamelCased method names.

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.