消息摘要--文件校验
import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import static org.junit.Assert.*;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
public class FileMD5
{
public static String
checkMessageDigest() throws Exception{
FileInputStream fis= new FileInputStream(new File("E:/ACM/in.txt"));
//初始化,并指定md5算法
DigestInputStream dis= new DigestInputStream(fis,MessageDigest.getInstance( "md5"));
byte[]
buffer=new byte[1024];
int readLen=dis.read(buffer,0,1024);//读,并且会update这个message
digest
while(readLen>-1){
readLen=dis.read(buffer, 0, 1024);
}
dis.close();
MessageDigest md=dis.getMessageDigest(); //获取消息摘要对象
byte[]
b=md.digest();//摘要处理
//十六进制处理
String md5Hex=Hex. encodeHexString(b);
System. out.println(md5Hex);
return md5Hex;
}
public static String
checkMessageDigestUtils() throws Exception{
FileInputStream fis= new FileInputStream(new File("E:/ACM/in.txt"));
String md5Hex=DigestUtils.md5Hex(fis);//包装,并获取md5,十六进制
fis.close();
System. out.println(md5Hex);
return md5Hex;
}
public static void main(String[]
args) throws Exception {
// TODO Auto-generated
method stub
String md51= checkMessageDigest();
String md52= checkMessageDigestUtils();
assertEquals(md51,md52);//判断两个方法计算的MD5值是否一致,不一致会抛出异常
}
}