我在 Nodejs 上有这段代码,我需要像 Java 一样编写,但结果不同。我认为问题出在十六进制编码上。但我不明白它是如何工作的。
Nodejs 代码:
crypto.createHash('sha256').update(seed, 'hex').digest()
Java代码:
digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(seedString);
最佳答案
这两个代码将为您提供相同的输出
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());
}
}
了解更多详情:
正如其他人所指出的,这取决于如何呈现数据。如果在 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
的作用
关于java - SHA-256 - NodeJS 和 Java 代码之间不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425424/