Sleds/libeye/java/com/sequencelogic/Digester.java

79 lines
2.2 KiB
Java
Raw Normal View History

2025-03-13 21:28:38 +00:00
package com.sequencelogic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Digest class for file and message comparison
public class Digester {
private static final char[] HexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final String digestName = "MD5";
private static MessageDigest digest;
static {
try {
digest = MessageDigest.getInstance (digestName);
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException ("Could not create an instance of " + digestName);
}
}
public Digester() {
}
public static String digest (File file) throws IOException {
digest.reset();
return encodeHex (digest.digest (getBytesFromFile (file)));
}
public static String digest (String string) {
digest.reset();
return encodeHex (digest.digest (string.getBytes()));
}
// Encode the digest as a hex encoded string
public static String encodeHex(byte[] data) {
int length = data.length;
char[] out = new char[length << 1];
for (int i = 0, j = 0; i < length; i++) {
out[j++] = HexDigits[(0xF0 & data[i]) >>> 4];
out[j++] = HexDigits[0x0F & data[i]];
}
return new String (out);
}
private static byte[] getBytesFromFile (File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException ("Digester: file cannot be NULL");
}
if (!file.exists() && !file.isFile()) {
throw new IllegalArgumentException("Digester: file must exist and be a file");
}
InputStream is = new FileInputStream (file);
long length = file.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Digester: read failed " + file.getName());
}
is.close();
return bytes;
}
}