[英]Android MD5 hash from contentresolver inputstream
我正在嘗試將文件從我的 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);
}
}
}
使用它來獲取哈希值
private String getFIleHashValue(File updateFile) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
Log.e("calculateMD5", "Exception while getting Digest", e);
return "";
}
InputStream is;
try {
is = new FileInputStream(updateFile);
} catch (FileNotFoundException e) {
Log.e("calculateMD5", "Exception while getting FileInputStream", e);
return "";
}
byte[] buffer = new byte[8192];
int read;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
// Fill to 32 chars
output = String.format("%32s", output).replace(' ', '0');
return output;
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e("calculateMD5", "Exception on closing MD5 input stream", e);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.