Pages

Friday, December 11, 2015

Spring Security with Md5 password encoder Authentication


Spring Security to a web application with md5 password encoder


  1. Required Maven Libraries:
  2.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-beans</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-config</artifactId>
    </dependency>
    
  3. Configuration files:
    1. MD5 Password Encoder script(md5encoder.sh)
    2. 1
      2
      3
      4
      5
      6
      7
      #!/bin/bash
      ##########################################################################
      # Name  : MD5 Password Encoder for PRISM API 
      ##########################################################################
      echo "Please enter password to be encoded:"
      read md5pass
      echo -n $md5pass | md5sum | awk '{print $1}'
      
    3. User Profiles(profiles.properties)
    4. 1
      2
      3
      # Basic Authentication credentials in APP
      # Format  is <username> = <md5encodedpassword>,<userRole>,<isUserEnabled> 
      candy=5f4dcc3b5aa765d61d8327deb882cf99,ROLE_USER,enabled
      
    5. Spring context xml(security-app-context.xml)
    6.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                 http://www.springframework.org/schema/security
                 http://www.springframework.org/schema/security/spring-security-3.1.xsd">
      
       <security:http entry-point-ref="authenticationEntryPoint"
        use-expressions="true">
        <security:intercept-url pattern="/**"  access="hasAnyRole ( 'ROLE_USER')" />
         <security:logout invalidate-session="true" delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE" />
        <security:custom-filter ref="basicAuthenticationFilter" position="BASIC_AUTH_FILTER" />
       </security:http>
       
       <bean id="basicAuthenticationFilter"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
        <property name="authenticationManager" ref="authManager" />
        <property name="authenticationEntryPoint" ref="authenticationEntryPoint" />
       </bean>
       <bean id="authenticationEntryPoint"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
        <property name="realmName" value="PRISM" />
       </bean>
      
       <bean id="md5encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
       </bean>
       <security:authentication-manager alias="authManager"> 
        <security:authentication-provider>
            <security:password-encoder ref="md5encoder" />
         <security:user-service id="userDetailsService" properties="file:{path}/profiles.properties"/>
        </security:authentication-provider>
       </security:authentication-manager>
      </beans>
      
    7. Web application xml(web.xml)
    8.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      <context-param>  
       <param-name>contextConfigLocation</param-name>  
       <param-value>file:{path}/security-app-context.xml</param-value>
      </context-param>
      <!-- security start -->
      <filter>
       <filter-name>springSecurityFilterChain</filter-name>
       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
      </filter>
      <filter-mapping>
       <filter-name>springSecurityFilterChain</filter-name>
       <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!-- security end -->
      

Tuesday, November 3, 2015

Read Keystore jks file by using Java KeyTool


Below command to read the jks file and display the certificates it contains:

>keytool -list -keystore keystore.jks
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 2 entries
activation, Mar 13, 2013, trustedCertEntry, Certificate fingerprint (SHA1): 85:4B:73:CE:00:86:D6:1B:FE:95:17:3D:BB:E6:BE:02:BB:78:A4:2F
selfsigned, Mar 13, 2013, PrivateKeyEntry, Certificate fingerprint (SHA1): C5:0A:C4:AB:DA:80:03:F7:59:C7:D9:02:C5:D7:9A:97:08:7B:83:A0

Above data says, it has 2 certificate entries,
first one is alias name is "activation"
2nd one is alias name is "selfsigned"

Now we can export the above two entries into Certificates in CRT files as below 

>keytool -exportcert -file keystore.crt -keystore keystore.jks -alias activation 
Enter keystore password: 
Certificate stored in file  <keystore.crt>
>keytool -exportcert -file keystore1.crt -keystore keystore.jks -alias selfsigned
Enter keystore password: 
Certificate stored in file <keystore1.crt>


Monday, November 2, 2015

Certificates Manipulation with Open SSL

Download Open ssl binaries for windows here: Windows Openssl.

Before Going to certificates we will go through the some talks below:

To Generate Certificate we need Private key, this key will be generated by RSA algorithm
RSA is a cryptosystem for private-key encryption, and is widely used for securing sensitive data over internet.
RSA stands for Rivest-Shamir-Adleman were the 3 persons last names who described the RSA algorithm.

.PEM Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.  
Normally it contains the chain of certificates.
.key This is a PEM formatted file containing just the private-key of a specific certificate
CSR is  Certificate Signing Request, basically this is the input file for generate Certificates(.CRT)
CRT is Certificate, which content not fully encoded certificate, it was same like .crt .cert, .cer
.pkcs12 .pfx .p12 Originally defined by RSA in the Public-Key Cryptography Standards, the "12" variant was enhanced by Microsoft. This is a passworded container format that contains both public and private certificate pairs. Unlike .pem files, this container is fully encrypted.

Steps to Generate Certificate
  1. Generate a private key using RSA
    >openssl genrsa -out root_ca.key 4096

    Loading 'screen' into random state - done
    Generating RSA private key, 4096 bit long modulus
    ....................................................
    ...................++
    e is 65537 (0x10001)

    If you want to password-protect this key, add option -des3.
  2. Generate Root CA certificate by any one of following ways:
    1.  Generate new root CA Certificate(.crt) directly by above private key
      The -x509 option is used for a self-signed certificate. 1826 days gives us a cert valid for 5 years.
      >openssl req -new -x509 -days 1826 -key root_ca.key -out root_ca.crt -sha256
      Loading 'screen' into random state - done
      You are about to be asked to enter information that will be incorporated
      into your certificate request.
      What you are about to enter is what is called a Distinguished Name or a DN.
      There are quite a few fields but you can leave some blank
      For some fields there will be a default value,
      If you enter '.', the field will be left blank.
      -----
      Country Name (2 letter code) [AU]:IN
      State or Province Name (full name) [Some-State]:TAMILNADU
      Locality Name (eg, city) []:MADRAS
      Organization Name (eg, company) [Internet Widgits Pty Ltd]:HCL
      Organizational Unit Name (eg, section) []:BROSS
      Common Name (e.g. server FQDN or YOUR name) []:RAJA
      Email Address []:RAJA@ERICSSON.COM
    2. Generate new root CA Certificate(.crt) using CSR(.csr)
      1. Generate CSR
        >openssl req -new -x509 -days 1826 -key root_ca.key -out root_ca.csr -sha256
        Loading 'screen' into random state - done
        You are about to be asked to enter information that will be incorporated
        into your certificate request.
        What you are about to enter is what is called a Distinguished Name or a DN.
        There are quite a few fields but you can leave some blank
        For some fields there will be a default value,
        If you enter '.', the field will be left blank.
        -----
        Country Name (2 letter code) [AU]:IN
        State or Province Name (full name) [Some-State]:TAMILNADU
        Locality Name (eg, city) []:MADRAS
        Organization Name (eg, company) [Internet Widgits Pty Ltd]:ERICSSON
        Organizational Unit Name (eg, section) []:CSI
        Common Name (e.g. server FQDN or YOUR name) []:SAISUDHAKAR
        Email Address []:ABC@DEF.COM

         
      2. Generate CRT by input the CSR
        >openssl x509 -days 3600 -in root_ca.csr -signkey root_ca.key -out root_csr_ca.crt
        Loading 'screen' into random state - done
        Getting Private key
            
  3. Create a Subordinate CA to used to under above Root CA
    1. First Generate Key:
      >openssl genrsa -out sub_ca.key 4096

      ..................................++
      ..............................++
      e is 65537 (0x10001)
    2. request a certificate for this subordinate CA:
      >openssl req -new -key sub_ca.key -out sub_ca.csr

      Loading 'screen' into random state - done
      You are about to be asked to enter information that will be incorporated
      into your certificate request.
      What you are about to enter is what is called a Distinguished Name or a DN.
      There are quite a few fields but you can leave some blank
      For some fields there will be a default value,
      If you enter '.', the field will be left blank.
      -----
      Country Name (2 letter code) [AU]:IN
      State or Province Name (full name) [Some-State]:TAMILNADU
      Locality Name (eg, city) []:MADRAS
      Organization Name (eg, company) [Internet Widgits Pty Ltd]:HCL
      Organizational Unit Name (eg, section) []:BROSS
      Common Name (e.g. server FQDN or YOUR name) []:JEAN
      Email Address []:JEAN@HCL.COM

      Please enter the following 'extra' attributes
      to be sent with your certificate request
      A challenge password []:password
      An optional company name []:IBM
    3. process the request for the subordinate CA certificate and get it signed by the root CA.
      >openssl x509 -req -days 730 -in sub_ca.csr -CA root_ca.crt -CAkey root_ca.key -set_serial 01 -out sub_ca.crt
      Loading 'screen' into random state - done
      Signature ok
      subject=/C=IN/ST=TAMILNADU/L=MADRAS/O=HCL/OU=BROSS/CN=JEAN/emailAddress=JEAN@HCL.COM
      Getting CA Private Key
      The cert will be valid for 2 years (730 days) and I decided to choose my own serial number 01 for this cert (-set_serial 01). For the root CA, I let OpenSSL generate a random serial number.
      Like above we can create multiple sub ordinate CA under Root CA.
  4. To package the keys and certs(root CA and all subordinate CA) in a PKCS12 file
    >openssl pkcs12 -export -out sub_ca.p12 -inkey sub_ca.key -in sub_ca.crt -chain -CAfile root_ca.crt
    Loading 'screen' into random state - done
    Enter Export Password:
    Verifying - Enter Export Password:


  5. To view CSR contains
    If it is self-signed(root) CSR
    >openssl x509 -text -noout -in root_ca.csr
    If it is not self-signed CA
    >openssl req -text -noout -in sub_ca.csr
  6. To view CRT contains
    >openssl x509 -text -noout -in root_ca.crt

Thursday, August 13, 2015

Merge Objects using Reflection API

Merging the two objects using Reflection API

For example the class Animal has objects Tiger, Lion, following is show how to merge these objects using Reflection API


1
2
3
4
5
6
7
8
9
class Animal
{
private name;
private age;
private weight;

..setter/getters

}


Main class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Class Main {
public static void main(String[] args)
{
    Animal tiger = new Animal();
    tiger.setName("Tiger");
    tiger.setAge("20");
    tiger.setWeight("80");
    Animal lion = new Animal();
    lion.setName("Lion");
    lion.setAge("25");
    lion.setWeight("120");
  
    merge(tiger,lion);
    
    sysout.println(tiger);
}

public static void merge(Object obj, Object update) {
       
        if (!obj.getClass().isAssignableFrom(update.getClass())) {
            return;
        }

        Method[] methods = obj.getClass().getMethods();

        for (Method fromMethod : methods) {
            if (fromMethod.getDeclaringClass().equals(obj.getClass())
                    && fromMethod.getName().startsWith("get")) {

                String fromName = fromMethod.getName();
                String toName = fromName.replace("get", "set");

                try {
                    Method toMetod = obj.getClass().getMethod(toName,
                            fromMethod.getReturnType());
                    Object value = fromMethod.invoke(update, (Object[]) null);
                    if (value != null) {
                        toMetod.invoke(obj, value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


Output:
[Lion, 25, 120]

Tiger objects properties were overriden by Lion object properties.


Tuesday, June 30, 2015

Post Json message to JMS Queue of Hornet Queue on JBoss

Here we do Posting the Json string contained JMS text message into a JMS HornetQ on Jboss server.
Here we are using Clustered based JMS setup on Jboss.

Test data contains the below json texts in *.json files.
For example TC1.json file contains below texts:
1
2
3
4
5
{
   "ID":"clkeidkerk948fjfmfkk49k",
   "name":"Purushottam",
   "value":"20000010"
}


Below are the steps:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.io.FileUtils;
import org.hornetq.api.core.DiscoveryGroupConfiguration;
import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.jms.client.HornetQConnectionFactory;

public class PostQueue {


    public static QueueConnection connection = null;

    public PostQueue() {
    }

    private void initJMSLister() {
 
 try {
     String discoveryGroupName = "dg-group1";
     String groupAddress = "231.7.7.7";
     int groupPort = 9876;
     int localPort = -1;
     String localBindAddress = "142.133.174.76";
     long refreshWaitTimeout = 1000;
     long initialWaitTimeout = 5000;
above is the starting the code .

Step2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
     UDPBroadcastGroupConfiguration udpConfig = new UDPBroadcastGroupConfiguration(groupAddress, groupPort, localBindAddress, localPort);
     System.out.println("udpConfig=\n" + udpConfig);
     DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration(discoveryGroupName, refreshWaitTimeout, initialWaitTimeout,udpConfig);
  System.out.println("groupConfiguration=\n" + groupConfiguration);
     HornetQConnectionFactory jmsConnectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(groupConfiguration,JMSFactoryType.CF);
  System.out.println("jmsConnectionFactory=\n" + jmsConnectionFactory);
  
     String queueName = "QueueName1";
     final Queue queue = HornetQJMSClient.createQueue(queueName);
     connection = jmsConnectionFactory.createQueueConnection("testuser", "testuser@1");
  System.out.println("connection=\n" + connection);
     final QueueSession session = connection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
     QueueReceiver receiver = session.createReceiver(queue);
     receiver.setMessageListener(new MessageListener() {
          @Override
          public void onMessage(Message message) {
            
            System.out.println("Message received.");
            TextMessage eventMessage = (TextMessage) message;
            String jsonEventMessage = null;
            try {
              jsonEventMessage = eventMessage.getText();
              
              System.out.println("Message Id: "+jsonEventMessage);
            }catch(Exception e){e.printStackTrace();}
            
          }
        });
     connection.start();


Step3: This part will explained in 3 sections as shown below:
Listener part:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
     System.out.println(" Event Queue Listerner Started");
     new Thread() {
  public void run() {
      System.out.println(" Event Queue Sender Started");
      try {
      javax.jms.QueueSender sender1 = session.createSender(queue);
   
            String[] ext = {"json"};
            Iterator<File> it = FileUtils.iterateFiles(new File("/opt/jboss/testjms/testdata"), ext, true);
            while(it.hasNext()){
              File test = (File)it.next();
              String tmp = FileUtils.readFileToString(test, "UTF-8");
              System.out.println(test.getName()+"\n"+tmp);
              
              TextMessage tm = session.createTextMessage(tmp);
              sender1.send(tm);
              
              System.out.println("msg. "+test.getName() + " sent.");
              Thread.sleep(1000);
            }
          } catch (Exception e1) {
            e1.printStackTrace();
          }
  }

     }.start();


Shutdown hook for JMS connection:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
     Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {   
   if(connection!=null)
    try {
        connection.close();
        System.out.println("connection closed");
    } catch (JMSException e) {
        e.printStackTrace();
    }
      }
     });

 } catch (Exception ee) {
     ee.printStackTrace();
 }
    }


Main method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static void main(String[] args) {

 try {
     PostQueue ab = new PostQueue();
     ab.initJMSLister();
 } catch (Exception ex) {
     ex.printStackTrace();
 }
    }
}

Tuesday, June 16, 2015

Spring JMS Complete Series

Part 1 Step1 : Build a Maven WebApp Project Step 2: Add the below dependencies:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<dependency>
     <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
</dependency>

Wednesday, June 3, 2015

Generate Serializable classes from XSD schema

Below is the code snippet to generate the serializable classes from Xsd schema xml:
Part 1: this section is normal to xsd file.
1
2
3
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://www.apertio.com/webservice/TmoUsEIRSoap/v1"
    xmlns:typens="http://www.apertio.com/webservice/TmoUsEIRSoap/v1"
Part 2: Below section is the required attributes/values to generate the serializable classes for xsd.
4
5
6
7
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc"
    jaxb:version="1.0" >
Part 3:Below section is the required xml tags to generate the serializable classes for xsd.
8
9
10
11
12
13
14
<xsd:annotation>
   <xsd:appinfo>
      <jaxb:globalBindings generateIsSetMethod="false">
         <xjc:serializable uid="1"/>
      </jaxb:globalBindings>
   </xsd:appinfo>
</xsd:annotation>
Part 4: Finally this section is normal to xsd file which contains the xsd elements.
15
16
17
18
19
20
21
22
23
24
25
<xsd:element name="QueryReq">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element type="xsd:integer" minOccurs="1" maxOccurs="1" name="tranId" />
            <xsd:element type="xsd:integer" minOccurs="1" maxOccurs="1" name="reqId" />
            <xsd:element type="xsd:integer" minOccurs="0" maxOccurs="1" name="version" />
            <xsd:element type="xsd:string" minOccurs="0" maxOccurs="1" name="capability" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>