【发布时间】:2016-04-27 09:44:47
【问题描述】:
我正在尝试将文件从我的 android 应用程序上传到我的服务器,为了确保它正确完成,我想添加 MD5 哈希。要上传的文件由 content:// Uri 引用。我使用下面的代码来计算我的 android 设备上的 MD5 哈希,并在我的服务器上使用稍微不同的代码(参见代码中的注释)。现在的问题是这两个没有给出相同的结果。我使用了一些第三方软件,我服务器上的 MD5 哈希实际上是正确的。我该如何解决?
public static String calculateMD5(Context context, Uri fileUri) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "Exception while getting digest", e);
return null;
}
InputStream is;
try {
is = context.getContentResolver().openInputStream(fileUri);
// is = new FileInputStream("some_file_location");
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, "Exception while getting FileInputStream", e);
return null;
}
byte[] buffer = new byte[8192];
int read;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : md5sum) {
String h = Integer.toHexString(0xFF & aMessageDigest);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Log.e(LOG_TAG, "Exception on closing MD5 input stream", e);
}
}
}
【问题讨论】: