MD5 PHP和android不尽相同 [英] md5 php and android not same

查看:132
本文介绍了MD5 PHP和android不尽相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计算文件的MD5,但得到不同的结果。

I am calculating the md5 of a file but getting different results

code:

 public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState);
AssetManager am = getResources().getAssets();
String as = null;
try {
    InputStream is=am.open("sdapk.db");
    as=is.toString();
}catch(IOException e) {
    Log.v("Error_E",""+e);
}
String  res = md5(as);
TextView tv = new TextView(this);
tv.setText(res);
setContentView(tv);
}
public String md5(String s) { 
try { 
    MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest();

 // Create Hex String
 StringBuffer hexString = new StringBuffer();
 for (int i=0; i<messageDigest.length; i++)
     hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();

} catch (NoSuchAlgorithmException e) {
 e.printStackTrace();
}
return "";
}

}

PHP MD5:E959637E4E88FDEC377F0A15A109BB9A

php md5 : E959637E4E88FDEC377F0A15A109BB9A

推荐答案

InputStream.toString()可能不会做你希望它是什么。这不是在正常的JDK覆盖,所以基本上 Object.toString() ...这将返回象java.io的字符串。 InputStream的@ 12345678。即使Android的东西,没有返回一个字符串,再presenting流的内容时,它会得到非常奇怪,因为你永远不指定要使用的编码字节转换为字符。

InputStream.toString() probably doesn't do what you want it to. It's not overridden in the normal JDK, so it's basically Object.toString()...which will return you a string like "java.io.InputStream@12345678". Even if Android's stuff did return a string representing the stream's contents, it'd get really weird since you never specify what encoding to use to convert bytes to chars.

您应该阅读,如果你想为MD5它的流。有点像

You should read the stream in if you want to MD5 it. Kinda like

private static char[] hexDigits = "0123456789abcdef".toCharArray();

public String md5(InputStream is) throws IOException
{
    byte[] bytes = new byte[4096];
    int read = 0;
    MessageDigest digest = MessageDigest.getInstance("MD5");
    while ((read = is.read(bytes)) != -1)
    {
        digest.update(bytes, 0, read);
    }

    byte[] messageDigest = digest.digest();

    StringBuilder sb = new StringBuilder(32);

    // Oh yeah, this too.  Integer.toHexString doesn't zero-pad, so
    // (for example) 5 becomes "5" rather than "05".
    for (byte b : messageDigest)
    {
        sb.append(hexDigits[(b >> 4) & 0x0f]);
        sb.append(hexDigits[b & 0x0f]);
    }

    return sb.toString();
}

这篇关于MD5 PHP和android不尽相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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