Archive

文章標籤 ‘md5’

檔案 md5 check 驗證

2008年7月18日 尚無評論

在網路上如何確認你下載的檔案是原作者的版本
或是在傳輸的過程中沒有遺失封包或被hacker從中加入什麼
所以可以用檢驗碼的方式來確認

目前最常在網路上被使用的就是MD5的檔案驗證機制,因為MD5加密後只要不同的data就會產生不同的驗證碼及不可逆的特性 不過近來已經有人稱可破解及找到碰撞可能,雖然出現了小瑕疵,不過因為使用方便及安全性還是足夠(破解可能性還是不普及)所以還是可以使用

以下是MD5的說明:
http://zh.wikipedia.org/wiki/MD5
http://a-010.cyut.edu.tw/~vote/md5.php

以下是Java的程式碼,傳入檔案進行MD5的驗證

File file = new File(“d:/1.dat”);
FileInputStream fs = new FileInputStream(file);
BufferedInputStream bi = new BufferedInputStream(fs);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] b = new byte[bi.available()];
int i;
while ((i = bi.read(b, 0, b.length)) != -1)
{
bo.write(b, 0, i);
}
bo.close();
System.out.print(Md5.MD5(new String(bo.toByteArray())));

public final static String MD5(String s)
{
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try
{
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance(“MD5”);
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++)
{
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
catch (Exception e)
{
return null;
}
}

程式來源:
http://www.j2megame.org/index.php/content/view/749/125.html

原作者的程式產出的MD5好像與網路上有提供的好像有差異
暫時先不去深入瞭解
反正功用達到就好~^^

Categories: JAVA Tags: