package transferterminate.business.util;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* <li>Title: IntegralityUtil.java</li>
* <li>Project: transferterminate</li>
* <li>Package:transferterminate.business.util</li>
* <li>Description: 摘要应用类</li>
* <li>Copyright: Copyright (c) 2009</li>
* <li>Company: IdealTechnologies </li>
* <li>Created on May 8, 2009 8:23:38 AM</li>
*
* @author chun_chang
* @version 1.0
*
*/
public class IntegralityUtil {
private static MessageDigest alg;
private static int length;
private static int maxBytesReadPerTime = 8192;
static {
try {
alg = MessageDigest.getInstance("MD5");
length = alg.getDigestLength();// 默认长度是16
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 获取文件内容的MD5摘要
* @param is:InputStream 源文件输入流
* @param fileLength:long 源文件长度
* @return byte[] 信息摘要
* @throws IDTException
*/
public static byte[] getMD5(InputStream is, long fileLength) throws Exception {
byte[] bytes = new byte[maxBytesReadPerTime];
int bytesRead = 0;
int maxReadTimesBeforeRedigest = 100;//每100块做一次摘要
byte[] digestOfPart = new byte[length];
byte[] digest = new byte[length * maxReadTimesBeforeRedigest];
int timesRead = 0;
byte[] digestToReturn = new byte[length];
try {
while (fileLength > 0) {
bytesRead = is.read(bytes);
digestOfPart = getMD5(bytes, 0, bytesRead);
System.arraycopy(digestOfPart, 0, digest, timesRead * length, length);
timesRead++;
if (timesRead == maxReadTimesBeforeRedigest) {
digestOfPart = getMD5(digest, 0, digest.length);
System.arraycopy(digestOfPart, 0, digest, 0, length);
timesRead = 1;
}
fileLength = fileLength - bytesRead;
}
if (timesRead > 1) {
digestOfPart = getMD5(digest, 0, timesRead * length);
System.arraycopy(digestOfPart, 0, digestToReturn, 0, length);
} else {
System.arraycopy(digest, 0, digestToReturn, 0, length);
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return digestToReturn;
}
/**
* 获取MD5信息摘要
* @param in:byte[] 源数据
* @return byte[] 信息摘要
* @throws Exception
*/
public static byte[] getMD5(final byte[] in) {
alg.update(in);
return alg.digest();
}
/**
* 获取MD5信息摘要
* @param in:byte[] 源数据
* @param from:int 起始字节
* @param len:int 长度
* @return byte[] 信息摘要
* @throws Exception
*/
public static byte[] getMD5(final byte[] in, int from, int len) {
alg.update(in, from, len);
return alg.digest();
}
/**
* 获取摘要长度
* @return int 摘要长度
*/
public static int getDigestLength() {
return length;
}
/**
* 设置每次读文件最大长度
* @param maxBytesReadPerTime
*/
public static void setMaxBytesReadPerTime(int maxBytesReadPerTime) {
IntegralityUtil.maxBytesReadPerTime = maxBytesReadPerTime;
}
}