之前在工作中需要使用MD5來判斷APK是否是同一個文件,開始服務(wù)端和客戶端使用MD5的方式是沒有問題的,但是隨著APK文件越來越多,有一天忽然發(fā)現(xiàn)同一個APK客戶端和服務(wù)端計算的MD5值不相同,導致APK上傳失敗問題,經(jīng)過仔細排查,發(fā)現(xiàn)客戶端生成的MD5少了一位,客戶端一直采用如下的方式計算.

通榆ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
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) {
}
當前名稱:MD5錯誤導致的血案
URL地址:http://www.jbt999.com/article0/gjsdio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、動態(tài)網(wǎng)站、網(wǎng)站策劃、電子商務(wù)、網(wǎng)站收錄、小程序開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)