在有关文件上传,下载时为了保证文件的安全和完整性都会考虑到验证文件的完整性操作。
在java中验证文件完整性的算法很多,不过今天我们只介绍一下使用MD5如何验证文件完整性;
public static void main(String[] args) throws IOException {
long begin = System.currentTimeMillis();
File file = new File("E:/unicom.sql");
String md5 = getFileMD5String(file);
//文件名不同,内容相同;
File file2 = new File("E:/unicom1.txt");
String md52= getFileMD5String(file2);
File file6 = new File("E:/unicom1.rar");
String md56= getFileMD5String(file6);
//文件名不同,内容不同;
File file3 = new File("E:/unicom2.sql");
String md53= getFileMD5String(file3);
//测试压缩包
File fileZip = new File("E:/mybatis-generator-core-1.3.2(1).zip");
String md5Zip= getFileMD5String(fileZip);
//测试压缩包
File fileZip2 = new File("E:/mybatis-generator-core-1.3.2.jar");
String md5Zip2= getFileMD5String(fileZip2);
System.out.println("MD5:"+md5);
System.out.println("MD5:"+md52);
System.out.println("MD5:"+md56);
System.out.println("MD5:"+md53);
System.out.println("MD5:"+md5Zip);
System.out.println("MD5:"+md5Zip2);
System.out.println("两个文件名不同,内同相同"+ checkPassword(md5, md52));
System.out.println("文件名不同,内容不同"+ checkPassword(md5, md53));
System.out.println("测试压缩包,内容不同"+ checkPassword(md5Zip, md5Zip2));
}
输出:
MD5:4d4a4a9a42863f5a1e3e3afb055e0d04
MD5:4d4a4a9a42863f5a1e3e3afb055e0d04
MD5:f7a6626347f8a104f99abb67c3297215
MD5:cad1f74a763045a5fe3d51cfeac23e50
MD5:2021e31fe251d6864dfb333aa58c87e6
MD5:2021e31fe251d6864dfb333aa58c87e6
两个文件名不同,内同相同true
文件名不同,内容不同false
测试压缩包,内容不同true
/**
* 生成文件的md5校验值
*
* @param file
* @return
* @throws IOException
*/
public static String getFileMD5String(File file) throws IOException {
InputStream fis;
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numRead);
}
fis.close();
return bufferToHex(messagedigest.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();
}
/**
* 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
*/
protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
stringbuffer.append(c0);
stringbuffer.append(c1);
}