Message Digest Algorithm
807603Dec 8 2007 — edited Dec 12 2007I tried to find out if my test method is working by comparing two different instances for the same file input, did some debugging print lines to show results, what makes it strange is, the two instances have the same inputed file "inputed it twice" and identical generated hex strings. But when compare them in an if statement using .equals() because they are strings (could this be the problem) I end up getting a negative result .
Could anyone help, please
/** Compares two different files */
public void compareFile(File fileA, File fileB) throws IOException, NoSuchAlgorithmException{
try {
DataInputStream inA = new DataInputStream(new FileInputStream(fileA)); // Input File
DataInputStream inB = new DataInputStream(new FileInputStream(fileB)); // Input File
byte[] bufferA = new byte[16384]; // we will read 16kB of data at once
byte[] bufferB = new byte[16384]; // we will read 16kB of data at once
int bytesReadA = 0;
int bytesReadB = 0;
int i = 0;
do{
bytesReadA = inA.read(bufferA); // read the block of data
bytesReadB = inB.read(bufferB); // read the block of data
MessageDigest algorithmA = MessageDigest.getInstance("SHA-1"); //Get a MessageDigest for the appropriate algorithm
MessageDigest algorithmB = MessageDigest.getInstance("SHA-1"); //Get a MessageDigest for the appropriate algorithm
algorithmA.update(bufferA); //Fill the digest's buffer with data to compute a message digest from bufferA
algorithmB.update(bufferB); //Fill the digest's buffer with data to compute a message digest from bufferA
byte[] digestA = algorithmA.digest(); // Generate the digest. This does any necessary padding required by the algorithm
byte[] digestB = algorithmB.digest(); // Generate the digest. This does any necessary padding required by the algorithm
StringBuffer hexStringA = new StringBuffer(); //Save or print digest bytes. If you happen to use Integer.toHexString(), remember that this doesn't print leading zeros
for (int k=0;k<digestA.length;k++) {
hexStringA.append(
Integer.toHexString(0xFF & digestA[k]));
hexStringA.append(" ");
}//end bufferA
StringBuffer hexStringB = new StringBuffer(); //Save or print digest bytes.
for (int l=0;l<digestB.length;l++) {
hexStringB.append(
Integer.toHexString(0xFF & digestB[l]));
hexStringB.append(" ");
}//end bufferB
System.out.println("Buffer A--" + " " + hexStringA.toString()); // print hex String
System.out.println("Buffer B--" + " " + hexStringB.toString()); // print hex String
if (hexStringA.equals(hexStringB)) // Compare if the strings are equal
{
System.out.println("Equal" + " " + i);
i++;
}
else
{
System.out.println("Not Equal");
}
}//End do Loop
while(bytesReadA == bufferA.length && bytesReadB == bufferB.length);
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}