Monday, 14 May 2012

An EJB that generates an SHA-1 of a form

My whim today, is to create an EJB that generates the SHA-1 message digest from the contents of a simple form.

I will be using GlassFish 3.1.2 to deploy my application. The SHA-1 is generated by using the MessageDigest class, found in the java.security package.

So, the first step is to create a Dynamic Web Project in Eclipse. It generates a default JSP. I use this page to hold the HTML contents of the form.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
     <meta http-equiv="Content-Type" content="text/html; 
                                           charset=UTF-8">
     <title>Test Form</title>
  </head>
  <body>
    <form method="POST" action="HashIt">
     Username: <input name="username"/> <br/>
     Password: <input name="password" type="password"><br/>
     <input type="submit" value="Submit">
    </form>
  </body>
</html> 
Then I create the servlet that processes this form. It does the following,
  • Receive the contents of the form (doPost)
  • Use the EJB to actually generate the SHA-1 and render the result
package com.whycouch;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class processes the requests from the form
 * @author Hathy
 */
@WebServlet("/HashIt")
public class HashIt extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @EJB
    private Hash hash;
 
    public HashIt() {
        super();        
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) 
                        throws ServletException, IOException {
           // Let us always use the doPost
           doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                       throws ServletException, IOException {

        String username=request.getParameter("username");
        String password=request.getParameter("password");
  
        if(username==null || username.length()==0)
           username="EMPTY";
        if(password==null || password.length()==0)
           password="EMPTY";
  
        response.getWriter().println(
             "The SHA-1 of the form data is "+
              hash.digest(username+password)
        );
 }
}
Finally, I create the EJB itself, which is nothing but a stateless session bean.
package com.whycouch;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import com.sun.xml.wss.impl.misc.Base64;

/**
 * This is the EJB that actually generates the SHA-1
 * for the input it is provided with
 * 
 * @author Hathy
 */
@Stateless
@LocalBean
public class Hash {
    
    MessageDigest sha1; 
    
    // Initialize the MessageDigest to use SHA-1
    // as its algorithm     
 
    public Hash() {
     try {
        sha1=MessageDigest.getInstance("SHA-1");
     } catch (NoSuchAlgorithmException e) { 
         System.err.println("Unable to find SHA-1");
     }
        System.out.println("Initialized");        
    }
    
    // Generate the message digest, and then convert it
    // into a Base64 string

    public String digest(String data){
     if(data==null) 
      return "";
     
     byte[] output = sha1.digest(data.getBytes());
     return Base64.encode(output);
    }
}
The Base64 utility class that I have used was found in the webservices-rt.jar, that comes along with the GlassFish server. So, when you run the application, and submit the form, you should see a message like,
The SHA-1 of the form data is yPf+Ow5BvoRtVodZLPIBj/biJoc=

No comments:

Post a Comment