NextHub

Development on NextHub has ceased. Click here to go to the SourceForge project page.

Hasher Update (and how to obtain the hash of a file in Java)

I updated Hasher today. The plugin still functions the same, but I fixed a bug in the hash generation algorithm (thanks to Vladimir Kozlov for pointing the bug out to me). I also greatly increased modularity which in turn reduced the code size rather significantly. Here is how I calculate the hash of a file (the String parameter algorithm can be any algorithm listed at http://java.sun.com/javase/6/docs/technotes/guides/security/StandardNames.html#MessageDigest):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
 
public static String generateHash(File file, String algorithm) throws NoSuchAlgorithmException, IOException {
	byte[] dataBytes = getFileContents(file);
	MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
	messageDigest.update(dataBytes);
	byte[] digestBytes = messageDigest.digest();
 
	// this chunk of code was taken from http://echochamber.me/viewtopic.php?f=11&t=16666&p=553936#p459685
	char[] hash = new char[2 * digestBytes.length];
	for (int i = 0; i < digestBytes.length; ++i) {
		hash[2 * i] = HEX_CHARS[(digestBytes[i] & 0xF0) >>> 4];
		hash[2 * i + 1] = HEX_CHARS[digestBytes[i] & 0x0F];
	}
 
	return new String(hash);
}
 
private static byte[] getFileContents(File file) throws IOException {
	FileInputStream fileInputStream = null;
 
	try {
		fileInputStream = new FileInputStream(file);
		byte fileBytes[] = new byte[fileInputStream.available()];
		fileInputStream.read(fileBytes);
		return fileBytes;
	} catch (IOException e) {
		throw e;
	} finally {
		if (fileInputStream != null)
			try {
				fileInputStream.close();
			} catch (IOException e) {
			} finally {
				fileInputStream = null;
			}
	}
}

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">