MD5 Checksum is used to check the integrity of a file. Before sending the file on the network , MD5Checksum will be calculated for the file (ie. md5Hash1) . After downloading the file again MD5Checksum is calculated (ie. md5hash2) . if md5Hash1 & md5Has2 is equal then the file is not modified or corrupted or not affected by virus.
In linux the following command is used to calculate the MD5Checksum of a file.
$ md5sum filename.
$ md5sum -c file.txt ---> file.txt will contain morethan one files with actual md5 values. The command will return OK, if the md5checksum of a file matches with the value in the file.txt .
The following code is for calculating the MD5Checksum of a file in Java.
public static String getMD5Checksum(String filename) throws Exception {
byte[] chkSum = Checksum(filename);
String md5ChkSum = "";
for (int i = 0; i < chkSum.length; i++) {
md5ChkSum += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return md5ChkSum;
}
public static byte[] Checksum(String filename) throws Exception {
InputStream fileinpstream = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest md = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fileinpstream.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fileinpstream.close();
return md.digest();
}
0 comments:
Post a Comment