md5 php和android不一样

时间:2011-12-01 06:09:06

标签: java android md5

我正在计算文件的md5但得到不同的结果

代码:

 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

1 个答案:

答案 0 :(得分:3)

InputStream.toString()可能不会做你想要的。它在正常的JDK中没有被覆盖,所以它基本上是Object.toString() ...它会返回一个像"java.io.InputStream@12345678"这样的字符串。即使Android的东西确实返回了表示流内容的字符串,但由于你从未指定用于将字节转换为字符的编码,所以它会变得非常奇怪。

如果你想MD5它,你应该读取流。有点像

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();
}