为什么我的Java和命令行SHA256输出不同?

Kev*_*ede 7 java sha256

我在命令行中使用散列字符串而不是在Android上的Java中获得不同的输出.我确定我做错了什么,但我看不出是什么.

命令行:

kevin@aphrodite:~$ echo derp | sha256sum
ee673d13de31533a375b41d9e57731d9bb4dbddbd6c1d2364f15be40fd783346  -
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

Java输出:

10-05 13:32:57.412: D/Config(12082): input hash: 3f4146a1d0b5dac26562ff7dc6248573f4e996cf764a0f517318ff398dcfa792
Run Code Online (Sandbox Code Playgroud)

这是bytesToHex(...)我在另一个问答中找到的方法.我确认通过记录Integer.toHexString(b)每个来做正确的事情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);
}
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 11

因为echo包括一个尾随的新行.您可以使用

echo -n derp | sha256sum
Run Code Online (Sandbox Code Playgroud)

添加\n到您的plaintext喜欢

final String plaintext = "derp\n";
Run Code Online (Sandbox Code Playgroud)