Java AWT MD5 applet-thingy

Published on . Takes less than 1 minute to read.

I made this little...thing as an exercise for my upcoming Java exam. It's a a graphical MD5 generator with a label, textbox and a button, using the AWT toolkit.

Hasher.java
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";
    }
    }
}

View gist on GitHub

Learningjavaappletawtmd5programming