1. CRC校验
CRC校验实用程序库 在数据存储和数据通讯领域,为了保证数据的正确,就不得不采用检错的手段。在诸多检错手段中,CRC是最著名的一种。CRC的全称是循环冗余校验。
其特点是:检错能力极强,开销小,易于用编码器及检测电路实现。从其检错能力来看,它所不能发现的错误的几率仅为0.0047%以下。从性能上和开销上考虑,均远远优于奇偶校验及算术和校验等方式。因而,在数据存储和数据通讯领域,CRC无处不在:著名的通讯协议X.25的FCS(帧检错序列)采用的是CRC-CCITT,ARJ、LHA等压缩工具软件采用的是CRC32,磁盘驱动器的读写采用了CRC16,通用的图像存储格式GIF、TIFF等也都用CRC作为检错手段。
Java中已经有实现好的校验函数,简单使用方法。
CRC32 crc32 = new CRC32();
crc32.update("abcdfg".getBytes());
System.out.println(crc32.getValue())
对于一个大文件,可以采用流的方式读取大文件
public static String getCRC32(File file) {
CRC32 crc32 = new CRC32();
//MessageDigest.get
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
crc32.update(buffer,0, length);
}
return crc32.getValue()+"";
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. MD5
Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。
Java也提供了一个函数来处理MD5。使用的是 java.security.MessageDigest 类。
MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能。消息摘要是安全单向散列函数,它采用任意大小的数据并输出一个固定长度的散列值。MessageDigest 对象在启动时被初始化。使用 update 方法处理数据。在任何地方都可调用 reset 复位摘要。一旦所有需要修改的数据都被修改了,将调用一个 digest 方法完成散列码的计算。对于给定次数的修改,只能调用 digest 方法一次。在调用 digest 之后,MessageDigest 对象被复位为初始化的状态。
public static String getMD5(File file) {
FileInputStream fileInputStream = null;
try {
MessageDigest MD5 = MessageDigest.getInstance("MD5");
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
return new String(Hex.encodeHex(MD5.digest()));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}