Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for accessing EncryptionFilter in Servlet
Previous Home Next

In this program, an Encryption Filter is used for transmitting data information into unreadable format. Steps involved in creating filter class and mapping it into web.xml file.check here.

Application directory structure

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">
 <filter>
  <filter-name>EncryptFilter</filter-name>
  <filter-class>r4r.Filter.EncryptFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>EncryptFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-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-index</title>
 </head>
 <body>
  <h1>Encryption Filter!R4R</h1>
  <form method="POST">
   Write Something: <textarea name="strings" 
           rows="3" cols="50"></textarea><br/>
   <input type="submit" value="Encrypt Data" /> 
   <input type="reset" value="Reset Data" />
  </form>
 </body>
</html>

Response.jsp Page

<%-- 
 Document: response.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-Encrypt</title>
 </head>
 <body>
  <h1>Data encrypted and decrypted!</h1>
  <!-- get attribute from request object -->
  <p>Encrypted Data: <strong> ${encrypted}</strong> </p>
  <p>Decrypted Data: <strong> ${decrypted}</strong> </p>
 </body>
</html>

Filter Program

/*
 * Save as a EncryptFilter.java
 */
package r4r.Filter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 *
 * @author R4R
 */
public class EncryptFilter implements Filter {

 private static final boolean debug = true;
 private FilterConfig filterConfig = null;

 // default constructor
 public EncryptFilter() {
 }

 /**
  * Init method for this filter 
  */
 @Override
 public void init(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  if (filterConfig != null) {
if (debug) {
 log("EncryptFilter:Initializing filter");
}
  }
 }

 /**
  * doFilter method for this filter
  */
 @Override
 public void doFilter(ServletRequest request,
	  ServletResponse response, FilterChain chain)
throws IOException, ServletException {
  if (debug) {
log("EncryptFilter:doFilter()");
  }
  if (request instanceof HttpServletRequest) {
String strings =
	((HttpServletRequest) request).getParameter("strings");
log("Message: " + strings);
if (strings != null) {
 try {
  /*
* Data Encrypt and Decrypt can be 
  perform through Triple-DES algorithm
* which initialize cryptographic cipher class 
for ENCRYPT_MODE and DECRYPT_MODE
*/
  KeyGenerator keygenerator = KeyGenerator.getInstance("DESede");
     // Triple-DES encryption 
  SecretKey secretkey = keygenerator.generateKey();
     //generate a secret/symmetric key
  Cipher cipher = Cipher.getInstance("DESede");
  cipher.init(Cipher.ENCRYPT_MODE, secretkey);
  byte[] encrypted = cipher.doFinal(strings.getBytes());
  cipher.init(Cipher.DECRYPT_MODE, secretkey);
  byte[] decrypted = cipher.doFinal(encrypted);

  // set attribute into request object
  request.setAttribute("encrypted", new String(encrypted));
  request.setAttribute("decrypted", new String(decrypted));
  //forward request object to another location 
  request.getRequestDispatcher
	   ("response.jsp").forward(request, response);
 } catch (Exception ex) {
  Logger.getLogger(EncryptFilter.class.getName()).log(Level.SEVERE,
 "Exception Generate in data encrypt and decrypt", ex);
 }
} else {
 chain.doFilter(request, response);
}
  }
 }

 /**
  * Return the filter configuration object for this filter.
  */
 public FilterConfig getFilterConfig() {
  return (this.filterConfig);
 }

 /**
  * Set the filter configuration object for this filter.
  */
 public void setFilterConfig(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
 }

 /**
  * Destroy method for this filter 
  */
 @Override
 public void destroy() {
  filterConfig = null;
 }

 /**
  * log method for print msg over server console
  */
 public void log(String msg) {
  filterConfig.getServletContext().log(msg);
 }
}
Output of Program
Previous Home Next