9

I'm getting different outputs from hashing a string on the command line vs. in Java on Android. I'm sure I'm doing something wrong, but I don't see what.

Command line:

kevin@aphrodite:~$ echo derp | sha256sum
ee673d13de31533a375b41d9e57731d9bb4dbddbd6c1d2364f15be40fd783346  -

Java:

final String plaintext = "derp";
final MessageDigest md;
try {
    md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
/* SHA-256 should be supported on all devices. */
    throw new RuntimeException(e);
}
final String inputHash = bytesToHex(md.digest(plaintext.getBytes()));
Log.debug(TAG, "input hash: " + inputHash);

Java output:

10-05 13:32:57.412: D/Config(12082): input hash: 3f4146a1d0b5dac26562ff7dc6248573f4e996cf764a0f517318ff398dcfa792

Here's the bytesToHex(...) method, which I found in another Q&A. I confirmed that it's doing the right thing by logging Integer.toHexString(b) for each b.

private static final char[] hexDigit = "0123456789abcdef".toCharArray();

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int i = 0; i < bytes.length; ++i) {
        int b = bytes[i] & 0xFF;
        hexChars[i * 2] = hexDigit[b >>> 4];
        hexChars[i * 2 + 1] = hexDigit[b & 0x0F];
    }
    return new String(hexChars);
}
2
  • 1
    Since the answer has already been established (\n in echo), might I also suggest that you can supplant your custom bytesToHex() in favor of DatatypeConverter.printHexBinary(byte[] val) Commented Oct 5, 2015 at 20:51
  • 1
    @Keith That doesn't exist in Android. Commented Oct 5, 2015 at 20:53

1 Answer 1

14

Because echo includes a trailing new-line. You can use

echo -n derp | sha256sum

or add \n to your plaintext like

final String plaintext = "derp\n";
Sign up to request clarification or add additional context in comments.

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.