【问题标题】:Why are my Java and command line SHA256 outputs different?为什么我的 Java 和命令行 SHA256 输出不同?
【发布时间】:2015-10-06 04:55:49
【问题描述】:

我在命令行上散列字符串与在 Android 上的 Java 中得到不同的输出。我确定我做错了什么,但我看不出是什么。

命令行:

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 输出:

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

这是我在另一个问答中找到的bytesToHex(...) 方法。我通过为每个 b 记录 Integer.toHexString(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);
}

【问题讨论】:

标签: java sha256


【解决方案1】:

因为echo 包含一个尾随换行符。你可以使用

echo -n derp | sha256sum

\n 添加到您的plaintext

final String plaintext = "derp\n";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多