Sometimes in programming world, there would be a requirement to generate a checksum out of the contents of a file. It would be for verifying if the contents of the file have been modified. Given a filepath [Any file type]. It generates a simple ‘SHA’ message digest.
[sourcecode language='java']
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class MyDigest {
public MyDigest(String Filename) {
// reads a file and calculates a message digest for it
File f = new File(Filename);
if (!f.exists()) {
System.out.println(”The file does not to exist”);
System.exit(1);
}
// Specify the number of lines in the files. Default capacity is 10.
java.util.List text = new ArrayList(1000); // 1000 lines as input
// Get an object that can compute an SHA message digest
MessageDigest digester = null;
try {
digester = MessageDigest.getInstance(”SHA”);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
// A stream to read bytes from the file f
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
// A stream that reads bytes from fis and computes an SHA message digest
DigestInputStream dis = new DigestInputStream(fis, digester);
// A stream that reads bytes from dis and converts them to characters
InputStreamReader isr = new InputStreamReader(dis);
// A stream that can read a line at a time
BufferedReader br = new BufferedReader(isr);
// Now read lines from the stream
try {
String line = “”;
while ((line = br.readLine()) != null
&& (line.indexOf(”")) != -1)
text.add(line);
} catch (IOException e3) {
e3.printStackTrace();
}
// Close the streams
try {
br.close();
} catch (IOException e4) {
e4.printStackTrace();
}
// Get the message digest
byte[] digest = digester.digest();
// warning: sun says to not use sun library methods
// there is no import because it is not available — just use library
String s = new sun.misc.BASE64Encoder().encode(digest);
System.out.println(s); // show user the encoded digest
System.exit(0);
// ==================================
}
public static void main(String[] args) {
MyDigest myDigest = new MyDigest(”C:\\COMLOG.txt”);
}
}
[/sourcecode]











Leave a Reply