【问题标题】:SHA-256 - mismatch between NodeJS and Java codeSHA-256 - NodeJS 和 Java 代码不匹配
【发布时间】:2018-05-20 00:14:48
【问题描述】:

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

Nodejs 代码:

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

Java 代码:

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

【问题讨论】:

  • 一个典型的种子有什么相似之处(是字符串还是二进制数据)?

标签: java node.js cryptography sha256


【解决方案1】:

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

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的作用

【讨论】:

  • 在上面的例子中,一切正常,但我的问题在于更新函数的第二个参数,即 encoding = hex。如果你设置了,结果会有所不同。在这个我的问题中,我不明白 encoding = hex 是什么。
  • @Павел 我根据您的评论改进了我的答案,希望现在一切都更清楚了
【解决方案2】:

来自nodejsdocumentation

使用给定数据更新哈希内容,其编码为 在 inputEncoding 中给出,可以是“utf8”、“ascii”或“latin1”。如果 未提供编码,数据为字符串,编码为 'utf8' 被强制执行。如果 data 是 Buffer、TypedArray 或 DataView,则 inputEncoding 被忽略。

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

PS。

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

【讨论】:

  • nodejs 上的代码是一个示例,它可以正常工作,问题出在 java 上的代码上。我阅读了文档,没有关于十六进制编码的消息。
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多