Java md5,PHP方式 [英] Java md5, the PHP way

查看:124
本文介绍了Java md5,PHP方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力工作几个小时,但我无法让它工作。

I have been working on this for hours, but I can't get it to work.

基本上我正在用Java开发一个用于REST服务器的REST客户端用PHP。客户端和服务器都必须计算字符串的md5,服务器将比较它们进行身份验证(kinda)。

Basically I am developing a REST client in Java for a REST server in PHP. Both the client and the server have to compute the md5 of a string and the server will compare them for authentication (kinda).

在服务器上,PHP代码是:

On the server, the PHP code is:

md5("getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff");

产生:

4d7b2e42c3dfd11de3e77b9fe2211b87

很好!

以下是客户端的代码:

import java.security.*;
....
String s = "getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff";
byte[] bytesOfMessage = s.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);    

System.out.println("String2: " + thedigest);        
System.out.println("String3: " + new String(thedigest));

产生:

String2: [B@42e816
String3: M{.B�����{��!�

如何让Java以与PHP相同的方式计算md5总和,请?

How can I get Java to compute the md5 sum the same way PHP does, please?

谢谢,
Dan

Thanks, Dan

推荐答案

试一试:

public static String md5(String input) throws NoSuchAlgorithmException {
    String result = input;
    if(input != null) {
        MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        while(result.length() < 32) { //40 for SHA-1
            result = "0" + result;
        }
    }
    return result;
}

来自 http://web.archive.org/web/20140209230440/http://www.sergiy.ca/how-to-make-java-md5-and-sha-1-hashes-compatible-with-php-or- mysql /

这篇关于Java md5,PHP方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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