Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL SHA256和Java MessageDigest SHA-256 don';不匹配_Java_Mysql_Encryption_Comparison_Sha256 - Fatal编程技术网

MySQL SHA256和Java MessageDigest SHA-256 don';不匹配

MySQL SHA256和Java MessageDigest SHA-256 don';不匹配,java,mysql,encryption,comparison,sha256,Java,Mysql,Encryption,Comparison,Sha256,我一直在尝试对项目中的一些用户密码进行加密,但似乎无法使其正常工作。我决定使用SHA-256算法,当我使用Sha2(例如256)向MySQL引入密码时,它会在加密的密码中添加两个零。在Java中,我曾经对程序中的文本进行散列,但不能得到相同的结果 try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest("Contrasenh

我一直在尝试对项目中的一些用户密码进行加密,但似乎无法使其正常工作。我决定使用SHA-256算法,当我使用Sha2(例如256)向MySQL引入密码时,它会在加密的密码中添加两个零。在Java中,我曾经对程序中的文本进行散列,但不能得到相同的结果

    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));
}
或者,如果你可以使用,整个事情可以做得更简单

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

这将在一行中提供(正确格式化)十六进制编码的SHA-256哈希。

您不能添加缺少的零吗

for (int i: hash) 
{
    if(Integer.toHexString(0xFF & i).length() == 2)
        hexString.append(Integer.toHexString(0xFF & i));
    else
        hexString.append ( 0x00 + Integer.toHexString(0xFF & i));
}

对我来说似乎没问题。

我甚至不知道可以在Java中的foreach循环中隐式转换为整数。很遗憾你不能把它也转换成正整数。非常感谢!我首先尝试使用字符串。格式。。。但它给了我一个完全不同的输出。所以我去了番石榴图书馆,我对它们印象深刻,我会经常使用它们。再次感谢!