什么是MD5
MD5即Message-Digest Algorithm 5(信息-摘要算法5)陨界,用于確保信息傳輸完整一致顿痪。是計(jì)算機(jī)廣泛使用的雜湊算法之一(又譯摘要算法镊辕、哈希算法),主流編程語言普遍已有MD5實(shí)現(xiàn)蚁袭。將數(shù)據(jù)(如漢字)運(yùn)算為另一固定長(zhǎng)度值征懈,是雜湊算法的基礎(chǔ)原理,MD5的前身有MD2揩悄、MD3和MD4受裹。
文件MD5的應(yīng)用場(chǎng)景
(1)加密
(2)在下載更新APK的時(shí)候,與遠(yuǎn)程服務(wù)器的MD5進(jìn)行匹配虏束,如果下載下來新文件的MD5的與遠(yuǎn)程的MD5一致棉饶,說明下載過程中沒有出現(xiàn)丟包。
如何獲取文件的MD5
private void getFile(){
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.d("ATG", path);
File file = new File(path+"/e8706cf83a2cda33dae5c40025922d75.apk");
String md5 = getFileMD5(file);
Log.d("ATG", md5);
}
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bytesToHexString(digest.digest());
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}