Skip to content

Instantly share code, notes, and snippets.

@anroots
Created May 11, 2012 01:44
Show Gist options
  • Save anroots/2656982 to your computer and use it in GitHub Desktop.
Save anroots/2656982 to your computer and use it in GitHub Desktop.
A graphical Java program that calculates the MD5 has of it's input.
import java.awt.*;
import java.awt.event.*;
import java.security.*;
import java.math.*;
/**
* A graphical Java program that calculates the MD5 has of it's input.
* @author anroots
*
*/
public class Hasher {
Frame window;
public static void main(String[] args) {
Hasher md5 = new Hasher();
}
/**
* Build the GUI and display it's contents. Call a method when the button is pressed.
*/
public Hasher() {
window = new Frame();
window.setSize(400,200);
window.setBackground(Color.pink);
window.setTitle("MD5 hash generator");
Label intro = new Label("Enter some text to generate a MD5 hash.");
intro.setForeground(Color.black);
TextField input = new TextField(10);
Button submit = new Button("Generate");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String input = ((TextField)((Component)e.getSource()).
getParent().getComponent (1)).getText();
((TextField)((Component)e.getSource()).
getParent().getComponent (1)).setText(hashThis(input));
}
});
window.setLayout(new GridLayout(3,2));
window.add(intro);
window.add(input);
window.add(submit);
window.setVisible(true);
}
/**
* Calculates the MD5 hash
* @param plaintext Input string
* @return MD5 of plaintext
*/
private static String hashThis(String plaintext) {
try {
// MD5 calculation code from:
//http://stackoverflow.com/questions/415953/generate-md5-hash-in-java/421696#421696
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
return hashtext;
} catch (Exception e) {
return "Computation error";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment