问题
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
回答1:
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.
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();
}
来源:https://stackoverflow.com/questions/8337226/md5-php-and-android-not-same