Skip to content

Instantly share code, notes, and snippets.

@brianewing
Created May 27, 2011 00:23
Show Gist options
  • Save brianewing/994401 to your computer and use it in GitHub Desktop.
Save brianewing/994401 to your computer and use it in GitHub Desktop.
URLHasher - Get MD5/SHA1/other MessageDigest hash of a URL's contents
package urlhasher;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class URLHasher {
private URL url;
private MessageDigest hash;
public URLHasher(URL url) throws AlgorithmNotFoundException {
this(url, "MD5");
}
public URLHasher(URL url, String algorithm) throws AlgorithmNotFoundException {
this.url = url;
try {
hash = MessageDigest.getInstance(algorithm);
} catch(NoSuchAlgorithmException nsae) {
throw new AlgorithmNotFoundException();
}
}
private InputStream getStream() throws IOException {
return url.openStream();
}
public String getHash() throws IOException {
InputStream inputStream = getStream();
int read;
byte[] dataTmp = new byte[4096];
while((read = inputStream.read(dataTmp)) != -1)
hash.update(dataTmp, 0, read);
byte[] hashDigest = hash.digest();
hash.reset();
return bytesToHex(hashDigest);
}
public static String bytesToHex(byte[] bytes) {
BigInteger bigInt = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bigInt);
}
class AlgorithmNotFoundException extends NoSuchAlgorithmException {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment