Last active
March 4, 2019 03:15
-
-
Save wuyisheng/f28746a40a36a2ec0241b36b20761856 to your computer and use it in GitHub Desktop.
simple util method for md5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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