哈希值就是文件的身份證,不過比身份證還嚴(yán)格。他是根據(jù)文件大小,時間,類型,創(chuàng)作著,機(jī)器等計算出來的,很容易就會發(fā)生變化,誰也不能預(yù)料下一個號碼是多少,也沒有更改他的軟件。哈希算法將任意長度的二進(jìn)制值映射為固定長度的較小二進(jìn)制值,這個小的二進(jìn)制值稱為哈希值。哈希值是一段數(shù)據(jù)唯一且極其緊湊的數(shù)值表示形式。如果散列一段明文而且哪怕只更改該段落的一個字母,隨后的哈希都將產(chǎn)生不同的值。要找到散列為同一個值的兩個不同的輸入,在計算上是不可能的。
消息身份驗(yàn)證代碼 (MAC) 哈希函數(shù)通常與數(shù)字簽名一起用于對數(shù)據(jù)進(jìn)行簽名,而消息檢測代碼 (MDC) 哈希函數(shù)則用于數(shù)據(jù)完整性。
package com.example.common;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class HashFile {
public static void main(String args[]) {
try {
System.out.println("32位:d71732f1187d2f008ad106c308d31947");
System.out.println(getMD5Checksum("E:\\定臺.pptx"));
}
catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename); //<span style="color: rgb(51, 51, 51); font-family: arial; font-size: 13px; line-height: 20px;">將流類型字符串轉(zhuǎn)換為String類型字符串</span>
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5"); //如果想使用SHA-1或SHA-256,則傳入SHA-1,SHA-256
int numRead;
do {
numRead = fis.read(buffer); //從文件讀到buffer,最多裝滿buffer
if (numRead > 0) {
complete.update(buffer, 0, numRead); //用讀到的字節(jié)進(jìn)行MD5的計算,第二個參數(shù)是偏移量
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
public static String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring(1);//加0x100是因?yàn)橛械腷[i]的十六進(jìn)制只有1位
}
return result;
}
}