Skip to content

Instantly share code, notes, and snippets.

@wuyisheng
Last active March 4, 2019 03:15
Show Gist options
  • Save wuyisheng/f28746a40a36a2ec0241b36b20761856 to your computer and use it in GitHub Desktop.
Save wuyisheng/f28746a40a36a2ec0241b36b20761856 to your computer and use it in GitHub Desktop.
simple util method for md5
package org.yeshen.download;
import android.support.annotation.WorkerThread;
import android.text.TextUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*********************************************************************
* This file is part of Download project
* Created by hello@yeshen.org on 2019/02/28.
* Copyright (c) 2019 yeshen, org. - All Rights Reserved
*********************************************************************/
public class Md5Util {
@WorkerThread
public static boolean check(File file, String md5) {
if (TextUtils.isEmpty(md5)) return false;
String calculatedDigest = calculate(file);
return md5.equalsIgnoreCase(calculatedDigest);
}
@WorkerThread
private static String calculate(File updateFile) {
if (updateFile == null || !updateFile.exists() || !updateFile.isFile()) return "";
byte[] buffer = new byte[8192];
InputStream is = null;
int read;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
is = new FileInputStream(updateFile);
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
String output = new BigInteger(1, digest.digest()).toString(16);
output = String.format("%32s", output).replace(' ', '0');
return output;
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
if (is != null) try {
is.close();
} catch (IOException e) {/*ignore,we have try out best*/}
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment