SHA-256 - NodeJS 和 Java 代码不匹配

SHA-256 - mismatch between NodeJS and Java code

我在 Nodejs 上有这段代码,我需要编写类似于 Java,但结果不同。我认为问题出在十六进制编码中。但是我不明白它是如何工作的。

Nodejs 代码:

crypto.createHash('sha256').update(seed, 'hex').digest()

Java代码:

digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(seedString);

来自 nodejs documentation:

Updates the hash content with the given data, the encoding of which is given in inputEncoding and can be 'utf8', 'ascii' or 'latin1'. If encoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.

简单来说,就是您提供的数据格式。

PS.

代码在更新中看起来有点错误,您将提供数据而不是种子。

这两个代码会给你相同的输出

NodeJS

var data = "seed";
var crypto = require('crypto');
crypto.createHash('sha256').update(data).digest("hex");

Java

import java.security.MessageDigest;

public class SHAHashingExample 
{
    public static void main(String[] args)throws Exception
    {
        String password = "seed";

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());

        byte byteData[] = md.digest();

        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        System.out.println("Hex format : " + sb.toString());

        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<byteData.length;i++) {
            String hex=Integer.toHexString(0xff & byteData[i]);
            if(hex.length()==1) hexString.append('0');
            hexString.append(hex);
        }
        System.out.println("Hex format : " + hexString.toString());
    }
}

更多详情:

NodeJS link
Java link

正如其他人所指出的,这取决于您如何呈现数据。如果在 update 函数中您没有指定任何内容 - 就像我上面给出的解决方案一样 - 您是在告诉将 seed 解释为使用默认的 UTF-8 编码进行编码。现在 UTF-8 字符串 seed 的十六进制翻译是什么?答案是 73656564,因为您可以轻松地从 this online tool

中查看示例

现在我们来验证一下。让我们写:

NodeJS

var data = "73656564";
crypto.createHash('sha256').update(data, 'hex').digest('hex');

你也会得到同样的结果。您告诉 update 函数,您提供的数据是 hex 表示,必须如此解释

希望这有助于阐明 hex

的作用