关于php MD5加密 与java MD5 加密结果不一致的问题

针对PHP不是UTF-8编码导致的问题

public String md5(String txt) {
             try{
                  MessageDigest md = MessageDigest.getInstance("MD5");
                  md.update(txt.getBytes("GBK"));    //问题主要出在这里,Java的字符串是unicode编码,不受源码文件的编码影响;而PHP的编码是和源码文件的编码一致,受源码编码影响。
                  StringBuffer buf=new StringBuffer();            
                  for(byte b:md.digest()){
                       buf.append(String.format("%02x", b&0xff));        
                  }
                 return  buf.toString();
               }catch( Exception e ){
                   e.printStackTrace(); 

                   return null;
                }
        }

或者直接使用PHP加密出来提供给JAVA使用

      1、搭建好php的环境(不作介绍),写一个通过提取get参数,并对值进行md5加密的页面,如下

   <?php echo strtoupper(md5($_GET["md5str"])); ?>

   strtoupper是字母大写转换的函数

   md5是MD5加密的函数

   $_GET["md5str"]就是通过url带一个md5str的参数,把值获取并打印出来

      2、JAVA页面的提交方法

     /**
     * 用于做PHP的提交处理
     * @param url
     */
    public static String phpRequest(String url){
        try{
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);//使用POST方式提交数据
            post.setRequestHeader("Content-Type","text/html; charset=UTF-8");
            client.executeMethod(post);
            String response = new String(post.getResponseBodyAsString().getBytes("8859_1"), "UTF-8");//打印结果页面
            post.releaseConnection();
            return response;
        } catch(IOException e){
            e.printStackTrace();
            return null;
        }
    }

需要提示的是,url记得先对中文参数进行一次UTF-8的编码再传到这个方法里面,这个方法对响应的结果做了反编码的处理,最后就能正确的返回php MD5加密后的值了!

原文地址:https://www.cnblogs.com/lbnnbs/p/5759597.html