您好,登錄后才能下訂單哦!
之前在工作中需要使用MD5來判斷APK是否是同一個文件,開始服務端和客戶端使用MD5的方式是沒有問題的,但是隨著APK文件越來越多,有一天忽然發(fā)現(xiàn)同一個APK客戶端和服務端計算的MD5值不相同,導致APK上傳失敗問題,經(jīng)過仔細排查,發(fā)現(xiàn)客戶端生成的MD5少了一位,客戶端一直采用如下的方式計算.
BigInteger bigInt = new BigInteger(1, digest.digest()); bigInt.toString(16);
這種方式來計算,后來通過驗證發(fā)現(xiàn),大部分時間這種方式是沒問題的,但是當遇到第一位數(shù)字是0時,就會發(fā)現(xiàn)得到的MD5把首位的0丟掉啦(很隱蔽的一個坑呀),原因是bigint進行16進制轉(zhuǎn)換的時候第一個0被自動去掉了
所以不建議使用這種方式來計算一個文件的MD5,可以使用下面的方式:
public class MD5Util { protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public synchronized static String getAgentMD5(String path) { File file = new File(path); if (!file.exists() || !file.isFile()) { System.out.println("文件不存在"); return null; } MessageDigest digest = null; FileInputStream fis = null; try { digest = MessageDigest.getInstance("MD5"); fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { digest.update(buffer, 0, numRead); } fis.close(); } catch (Exception e) { // TODO: handle exception } return bufferToHex(digest.digest()); } private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字節(jié)中高 4 位的數(shù)字轉(zhuǎn)換, char c1 = hexDigits[bt & 0xf];// 取字節(jié)中低 4 位的數(shù)字轉(zhuǎn)換 stringbuffer.append(c0); stringbuffer.append(c1); } public static void main(String[] args) { }
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。