Skip to content

Instantly share code, notes, and snippets.

@bluepapa32
Created January 7, 2010 07:09
Show Gist options
  • Save bluepapa32/271060 to your computer and use it in GitHub Desktop.
Save bluepapa32/271060 to your computer and use it in GitHub Desktop.
MD5 with Java
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static void main(String[] args)
throws IOException, NoSuchAlgorithmException {
InputStream in = new FileInputStream(args[0]);
try {
System.out.println(md5(in));
} finally {
in.close();
}
System.out.println(md5(args[0].getBytes()));
}
public static String md5(byte[] b)
throws IOException, NoSuchAlgorithmException {
return md5(new ByteArrayInputStream(b));
}
public static String md5(InputStream in)
throws IOException, NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buf = new byte[1024];
int i = 0;
while ((i = in.read(buf)) > -1) {
md5.update(buf, 0, i);
}
return toHexString(md5.digest());
}
public static String md5(ReadableByteChannel r)
throws IOException, NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
ByteBuffer buf = ByteBuffer.allocate(1024);
while (r.read(buf) > -1) {
buf.flip();
md5.update(buf);
buf.clear();
}
return toHexString(md5.digest());
}
private static String toHexString(byte[] b) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < b.length; i++) {
int x = b[i] & 0xff;
if (x < 0x10) {
s.append("0");
}
s.append(Integer.toHexString(x));
}
return s.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment