Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, August 19, 2016

How to encrypt string in Java


Security is important for Business to assurance that you have all proper security systems in place. Encrypting user related information like phone number, password, credit card always assure that their information are safe and secure.  Almost all modern applications need, in one way or another, encryption plays vital role to empower the business. 

The MD5 algorithm is a widely used hash function producing a 128-bit hash value. So, we will create a class with single method to get encrypted value of a String.



import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class md5Hash {
    public static String getEncrypted(String password) {
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
            m.update(password.getBytes(), 0, password.length());
            return (new BigInteger(1, m.digest()).toString(16));
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(md5Hash.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}

Now, you can simply call this method as shown below to get encrypted string 

String encrypted = md5Hash.getEncrypted(password);

Monday, August 15, 2016

How to display client IP Address


Some time you may want to show or capture client IP address for security reasons. Here are sample codes specific to language/script. 

PHP :

 echo $_SERVER[‘REMOTE_ADDR'];  


Java :


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class IPAddress{
    public static void main(String[] a) {

        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            System.out.print(thisIp.getHostAddress());     
        } catch (UnknownHostException ex) {
            Logger.getLogger(study.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

C# :


protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}


VB.Net :


Public Shared Function GetIPAddress() As String
    Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
    Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If String.IsNullOrEmpty(sIPAddress) Then
        Return context.Request.ServerVariables("REMOTE_ADDR")
    Else
        Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
        Return ipArray(0)
    End If
End Function

Javascript :


$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
  obj = JSON.parse(JSON.stringify(data, null, 2));
  $('#ip').html(obj.ip);
});


Basics of Java Servlet


What is Servlet ?


A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Servlets also have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines lifecycle methods. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.


Servlet Lifecycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet


  1. Servlet Initialization using init() method
  2. The servlet is initialized by calling the init () method. It is used for one-time initializations and called when the servlet is first created, not for each user request.

  3. Serving Client Request using service() method
  4. The servlet calls service() method to process a client's request. Each time the server receives a request for a servlet, the server creates a new thread and calls service. The service() method checks the HTTP request type (GET, POST etc.) and calls doGet, doPost etc. methods as appropriate.

  5. Reallocating memory using destroy() method
  6. The servlet is terminated by calling the destroy() method. It allows developers to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

Finally, servlet is garbage collected by the garbage collector of the JVM.





Advantage of Servlet


1. Servlets provide a way to generate dynamic documents that is both easier to write and faster to run.
2. provide all the powerful features of JAVA, such as Exception handling and garbage collection.
3. Servlet enables easy portability across Web Servers.
4. Servlet can communicate with different servlet and servers.
5. Since all web applications are stateless protocol, servlet uses its own API to maintain  session


URL Mapping


When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets. 
<servlet> <servlet-name>AddPhotoServlet</servlet-name> //servlet name <servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class </servlet> <servlet-mapping> <servlet-name>AddPhotoServlet</servlet-name> //servlet name <url-pattern>/AddPhotoServlet</url-pattern> //how it should appear </servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Rule 1 : 

The server context on the servlet container matches the pattern in /inbox/* as follows:

http://apptech-solution.blogger.in/inbox/synopsis               <—Correct
http://apptech-solution.blogger.in/inbox/complete?date=today     <— Correct
http://apptech-solution.blogger.in/inbox                           <— Correct
http://apptech-solution.blogger.in/server1/inbox                     <—  Incorrect

Rule 2 :

A context located at the path /geo matches the pattern in *.map as follows:

http://apptech-solution.blogger.in/geo/US/Oregon/Portland.map    <—Correct
http://apptech-solution.blogger.in/geo/US/server/Seattle.map   <—Correct
http://apptech-solution.blogger.in/geo/Paris.France.map          <—Correct
http://apptech-solution.blogger.in/geo/US/Oregon/Portland.MAP   <—Incorrect (case-sensitive)
http://apptech-solution.blogger.in/geo/US/Oregon/Portland.mapi <—Incorrect

Rule 3 :

A mapping that contains the pattern / matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.


The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.