Al Lelopath
Al Lelopath

Reputation: 6778

Hash of byte array in Java

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.

Upvotes: 1

Views: 3004

Answers (2)

Sam
Sam

Reputation: 9952

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.

Upvotes: 4

weston
weston

Reputation: 54811

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.

Upvotes: 2

Related Questions