Why Your SHA-256 Hash in Android Looks Like Gibberish
You are likely encountering this issue because of a fundamental mismatch between how Java's MessageDigest class represents data and how most developers expect to read it. The core problem isn't with the hashing algorithm itself; SHA-256 is robust and widely supported. The error stems from trying to convert a byte array directly into a string using String.toString().
In your Java code, you executed:
digest.digest(password.getBytes("UTF-8")).toString()
When you pass a byte array to the .toString() method in Java, it does not interpret those bytes as a hexadecimal representation. Instead, it calls the default toString implementation of the byte[] class. This results in a string that looks like [B@15db9742, or in some environments/versions, a seemingly random alphanumeric sequence like "a42yzk3axdv3k4yh98g8". This output is simply the object's memory address representation, not the actual hash content.
To match the PHP output f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b, you must explicitly convert the raw byte array into a hexadecimal string. The standard Java utility BigInteger is the most reliable way to handle this conversion without relying on third-party libraries like Apache Commons Codec, although those are often preferred for production systems due to better performance and additional features.
Here is the corrected approach using standard JDK classes:
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtil {
public static String getSha256Hash(String input) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// It is good practice to reset the digest if you plan to reuse the instance,
// though for a one-shot hash operation this is not strictly necessary.
digest.reset();
byte[] hashBytes = digest.digest(input.getBytes(java.nio.charset.StandardCharsets.UTF_8));
// Convert byte array to Hex String
return bytesToHex(hashBytes);
}
private static String bytesToHex(byte[] bytes) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length * 2) + "x", bi).toLowerCase();
}
}
Why BigInteger Works Here
The logic relies on how binary data maps to text. A byte array consists of integers ranging from -128 to 127. When you pass this array to new BigInteger(1, bytes), the constructor interprets the two's complement representation of the bytes as a positive integer (the signum bit is forced to 0).
Once you have that large integer, formatting it with %x converts every byte into its two-character hexadecimal equivalent. The format string "%0" + (data.length*2) + "X" ensures that even if the resulting hash starts with a zero (which happens frequently in SHA-256), those leading zeros are preserved. Without the width specifier, BigInteger.toString() would simply drop the leading zeros, resulting in an incorrect hash length of less than 64 characters.
Best Practices and Trade-offs
While this implementation uses only standard libraries, you should consider the context of your application. If you are building a production-grade Android app, relying solely on java.math.BigInteger for hashing can be inefficient if called frequently in loops or within high-performance cryptographic routines. In those scenarios, using javax.crypto.Cipher with the HmacSHA256 algorithm is generally preferred for message authentication codes, or utilizing libraries like Bouncy Castle which offer optimized hex conversion utilities.
Furthermore, never store raw passwords; always hash them before storing or transmitting them over the network. However, note that SHA-256 alone is not sufficient for password storage due to its speed. Attackers can brute-force hashes quickly if they are not using a salt or a key derivation function like Argon2 or PBKDF2. The example provided above calculates the hash of the string "asdf", which matches your PHP reference exactly, but remember that in a real-world scenario, you must append a unique random salt to every password before hashing it.
For developers working with Laravel ecosystems who need to integrate this logic into their backend services, checking how Laravel handles hashing in its built-in facades can provide valuable context on best practices for secure storage.