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

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

问题描述

PHP 代码:

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

PHP 输出:

cdf30c6b345276278bedc7bcedd9d5582f5b8e0c1dd858f46ef4ea231f92731d

cdf30c6b345276278bedc7bcedd9d5582f5b8e0c1dd858f46ef4ea231f92731d

Java 代码:

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 输出:

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

-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?

我犯了一个错误,无论如何我想我现在已经有了问题的答案.

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

推荐答案

好吧,第一件事就是使用一致的字符串编码.我不知道 PHP 会做什么,但是 "jake".getBytes() 将使用您的平台默认编码为 Java.这是一个非常糟糕的主意.假设 PHP 开始处理 Unicode 字符串,那么使用 UTF-8 可能是一个好的开始.(如果不是,您需要弄清楚它正在做什么并尝试使两者保持一致.)在 Java 中,使用 String.getBytes()<的重载/code> 采用 Charset 或采用 Charset 名称的.(我个人喜欢用 Guava 的 Charsets.UTF_8.)

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.)

然后说服 PHP 也使用 UTF-8.

Then persuade PHP to use UTF-8 as well.

然后以十六进制输出Java结果.我非常怀疑您提供的代码是您正在运行的实际代码,否则我希望输出诸如[B@e48e1b".无论您在做什么将字节数组转换为字符串,请将其更改为使用十六进制.

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天全站免登陆