Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for encrypt and decrypt data through servlet
Previous Home Next

In this program, data is encrypt and decrypt through servlet.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
     <servlet-name>encryptDataServlet</servlet-name>
     <servlet-class>r4r.servlet.encryptDataServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>encryptDataServlet</servlet-name>
     <url-pattern>/encryptDataServlet</url-pattern>
   </servlet-mapping>
   <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Index.jsp

<%-- 
 Document   : index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type"
	      content="text/html; charset=UTF-8">
        <title>r4r.co.in-servlet</title>
    </head>
    <body>
      <form>
       <h1>Access Servlet by servlet's Name!</h1>
       <a href="encryptDataServlet">encryptDataServlet</a>
        </form>
    </body>
</html>

Servlet Program

/*
 * Save as a encryptDataServlet.java
 */
package r4r.servlet;
import java.io.*;
import java.util.logging.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.security.*;
import javax.crypto.*;
/**
 *
 * @author R4R
 */
public class encryptDataServlet extends HttpServlet {

 protected void processRequest
  (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  try {
/* TODO output your page here */
out.println("<html>");
out.println("<head>");
out.println("<title>" + getServletInfo() + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet encryptDataServlet at "
            + request.getContextPath() + "</h1>");
out.println
	("<form action=\"encryptDataServlet\" method=\"POST\">");
out.println("Enter Message: <textarea name=\
                   "data\" rows=\"2\" cols=\"25\"></textarea>");
out.println("<input type=\"submit\
                    " value=\"Encrypt Data\" />");
out.println("<input type=\"reset\" value=\"Reset\" />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
  } finally {
out.close();
  }
 }

 @Override
 protected void doGet
 (HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
  processRequest(request, response);
 }

 @Override
 protected void doPost
  (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  String data = request.getParameter("data");
  try {
if (!data.equals("")) {
 //Invoke method 
 processHeader(out);
 processBody(out, data);
 processFooter(out);
} else {
 out.println("Don't leave any text empty");
 out.println
("<BR><a href=\"encryptDataServlet\">Return to Home Page</a>");
}
  } finally {
//free resource
out.flush();
out.close();
  }
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-encryptDataServlet";
 }

 // method haldel Form header
 protected void processHeader
	 (PrintWriter out) throws ServletException, IOException {
  out.println("<html>");
  out.println("<head>");
  out.println("<title>" + getServletInfo() + "</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h1> Encrypt & Decrypted Data</h1>");
 }

 // method handel Form Body
 protected void processBody
	(PrintWriter out, String data)
	 throws ServletException, IOException {
  try {
// Generate encryption keys with a KeyGenerator object
KeyGenerator keygenerator = 
	KeyGenerator.getInstance("DESede");  // Triple-DES encryption 
SecretKey secretkey = keygenerator.generateKey(); // Generate a key
// Obtain an object to perform encryption or decryption
Cipher cipher = Cipher.getInstance("DESede");
// Initialize the cipher object for encryption
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
// Convert data into byte and encrypt it
byte[] encrypted = cipher.doFinal(data.getBytes());
// Initialize the cipher object for deEncryption
cipher.init(Cipher.DECRYPT_MODE, secretkey);
byte[] decrypted = cipher.doFinal(encrypted);
// Print output data over browser
out.println("<BR>Encrypted text : " + new String(encrypted));
out.println("<BR>Decrypted text : " + new String(decrypted));

  } catch (IllegalBlockSizeException ex) {
Logger.getLogger(encryptDataServlet.class {}.getName()).
	log(Level.SEVERE, "IllegalBlockSizeException Generate", ex);
  } catch (BadPaddingException ex) {
Logger.getLogger(encryptDataServlet.class.getName()).
	   log(Level.SEVERE, "BadPaddingException Generate", ex);
  } catch (InvalidKeyException ex) {
Logger.getLogger(encryptDataServlet.class.getName()).
	 log(Level.SEVERE, "InvalidKeyException Generate", ex);
  } catch (NoSuchPaddingException ex) {
Logger.getLogger(encryptDataServlet.class.getName()).
	log(Level.SEVERE, "NoSuchPaddingException Generate", ex);
  } catch (NoSuchAlgorithmException ex) {
Logger.getLogger(encryptDataServlet.class.getName()).
	 log(Level.SEVERE, "NoSuchAlgorithmException Generate", ex);
  }
 }

 // method handel form footer
 protected void processFooter
	 (PrintWriter out) throws ServletException, IOException {
  out.println("</body>");
  out.println("</head>");
  out.println
 ("<BR><a href=\"encryptDataServlet\">Return to Home Page</a>");
 }
}
Output of Program
Previous Home Next