MySQL SHA256和Java MessageDigest SHA-256不匹配

我一直在尝试加密一个项目的一些用户密码,但我似乎无法让它正常工作.我决定使用SHA-256算法,当我使用Sha2向MySQL引入密码时(例如,256)它为加密密码添加了两个零.在Java中,我使用this来散列程序中的文本,但无法获得相同的结果.

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest("ContrasenhaPassword".getBytes("UTF-8"));

        StringBuilder hexString = new StringBuilder();
        for (int i: hash) {
            hexString.append(Integer.toHexString(0XFF & i));
        }
        String Hashed = new String(hexString);
        System.out.println(hexString);
        System.out.println(Hashed);
        // Below, MySQL Output for SHA2('ContrasenhaPassword',256)
        System.out.println("d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78");
        System.out.println(Hashed.equals(hexString));
        } catch (Exception e) {
        e.printStackTrace();
        }

我得到的输出是:

        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78
        false 
        BUILD SUCCESSFUL (total time: 0 seconds)

有任何想法吗?

解决方法:

区别在于你如何打印它们:

for (int i: hash) {
  hexString.append(Integer.toHexString(0XFF & i));
}

留下前导零,因此有一个字节格式为“e”而不是“0e”.可能是最简单的替代方案

for (int i: hash) {
  hexString.append(String.format("%02x", i));
}

或者,如果你可以使用Guava,整个过程可以更简单地完成

Hashing.sha256().hashString("ContrasenhaPassword", Charsets.UTF_8).toString()

它在一行中为您提供(格式正确的)十六进制编码的SHA-256哈希.

上一篇:字节流和字符流的结构小解


下一篇:keepalive配置(转载)