Java SHA256输出不同的哈希到PHP SHA256? [英] Java SHA256 outputs different hash to PHP SHA256?

查看:1368
本文介绍了Java SHA256输出不同的哈希到PHP SHA256?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP代码:



echo hash('sha256','jake');



PHP输出:

cdf30c6b345276278bedc7bcedd9d5582f5b8e0c1dd858f46ef4ea231f92731d

Java代码: p>

  String s =jake; 
MessageDigest md = MessageDigest.getInstance(SHA-256);
md.update(s.getBytes(Charset.forName(UTF-8)));
byte [] hashed = md.digest();
String s2 =;
(字节b:散列){
s2 + = b;
}
System.out.println(s2);

Java输出:

-51- 1312107528211839-117-19-57-68-19-39-43884791-1141229-4088-12110-12-223531-11011529

我原本以为这两个人会返回相同的结果。显然,情况并非如此。我怎么能得到这两个匹配或不可能?
$ b编辑:我犯了一个错误,认为我现在有问题的答案了。

解决方案

那么,你需要做的第一件事情就是使用一致的字符串编码。我不知道PHP会做什么,但是jake.getBytes()将使用Java的平台默认编码。这是一个非常糟糕的主意。使用UTF-8可能会是一个好的开始,假设PHP应对Unicode字符串开始。 (如果没有,你需要确定它正在做什么,并试图使它们保持一致。)在Java中,使用的重载。String.getBytes (),它需要一个 Charset 或采用 Charset 的名称。 (我个人喜欢使用Guava的 Charsets.UTF_8 。)

然后说服PHP使用UTF-8以及。

然后以十六进制输出Java结果。我非常怀疑你给出的代码是你正在运行的实际代码,否则我期望输出如[B @ e48e1b。无论您将字节数组转换为字符串,将其更改为使用十六进制。


PHP code:

echo hash('sha256', 'jake');

PHP output:

cdf30c6b345276278bedc7bcedd9d5582f5b8e0c1dd858f46ef4ea231f92731d

Java code:

String s = "jake";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(s.getBytes(Charset.forName("UTF-8")));
byte[] hashed = md.digest();
String s2 = "";
for (byte b : hashed) {
    s2 += b;
}
System.out.println(s2);

Java output:

-51-1312107528211839-117-19-57-68-19-39-43884791-1141229-4088-12110-12-223531-11011529

I had expected the two to return the same result. Obviously, this is not the case. How can I get the two to match up or is it impossible?

EDIT: I had made a mistake, think I have the answer to the question now anyway.

解决方案

Well, the very first thing you need to do is use a consistent string encoding. I've no idea what PHP will do, but "jake".getBytes() will use whatever your platform default encoding is for Java. That's a really bad idea. Using UTF-8 would probably be a good start, assuming that PHP copes with Unicode strings to start with. (If it doesn't, you'll need to work out what it is doing and try to make the two consistent.) In Java, use the overload of String.getBytes() which takes a Charset or the one which takes the name of a Charset. (Personally I like to use Guava's Charsets.UTF_8.)

Then persuade PHP to use UTF-8 as well.

Then output the Java result in hex. I very much doubt that the code you've given is the actual code you're running, as otherwise I'd expect output such as "[B@e48e1b". Whatever you're doing to convert the byte array into a string, change it to use hex.

这篇关于Java SHA256输出不同的哈希到PHP SHA256?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆