Adding Certificate files to Java KeyStore

Introduction SSL

Most of those sites use the Socket Layer (SSL) protocol to secure their Internet applications.

SSL allows the data from a client, such as a Web browser, to be encrypted prior to transmission so that someone trying to sniff the data is unable to decipher it.

Many Java application servers and Web servers support the use of keystores for SSL configuration.

If you’re building secure Java programs, learning to build a keystore is the first step.

Source :
http://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html#introduction

 

What is Java Key Tool ?

Java Keytool is a key and certificate management utility. It allows users to manage their own public/private key pairs and certificates.
Java Keytool stores the keys and certificates in what is called a keystore. It protects private keys with a password.

Each certificate in a Java keystore is associated with a unique alias.
When creating a Java keystore you will first create the .jks file that will initially only contain the private key,
then generate a CSR. Then you will import the certificate to the keystore including any root certificates.

Source:
http://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html#keytool

 

Steps to manually import certficicates into KeyStore

 

1. Create a KeyStore in machine

keytool -keystore <KeyStoreName> -genkey -alias <Key Store Alias>
eg:
keytool -keystore mykeystore -genkey -alias myalias

 

refer:
https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html

 

2. Get the Certificate File and keep it in a location

eg: Certificate file name is scarlet.cer

 

3. Import the Certificate as a Trusted Certificate to keystore

keytool -import -alias <AliasName> -keystore <KeyStoreName> -file <FilePath>
eg:
keytool -import -alias susan -keystore mykeystore -file scarlet.cer

 

Posted in Uncategorized

Java Program Code Obfuscation for Secure Software

What is the mean of Obfuscation?

Obfuscation (or beclouding) is the hiding of intended meaning in communication, making communication confusing, willfully ambiguous, and harder to interpret.[citation needed] The word comes from Latin obfuscatio, from obfuscare (“to darken”), from ob (“over”) and fuscare (“to make dark”), from fuscus (“dark”). Obfustication is a common variant, especially in British English.

 

Protect Your Java Code — Through Obfuscators And Beyond

Reverse engineering of your proprietary applications by unfair competition or malicious hackers may result in highly undesirable exposure of your algorithms and ideas, proprietary data formats, licensing and security mechanisms, and, most importantly, your customers’ data. Here is why Java is particularly weak in this respect compared to C++:

 

What is Progurad ?

ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or higher, or for Java Micro Edition.

Refer-  http://proguard.sourceforge.net/index.html#manual/examples.html

 

How to Use Progurad with Maven for code Obfuscation ? 

It is possible to obfuscate Java Code using Maven targets. It is need to use compatible Maven Plugin with compatible Proguard Version.

It is very easy to use Proguard with Maven. Just need to add correct versions in pom.xml under plugin section.

 

 

Following is working example for Obfuscate java code using Proguard. 

Here jdk version is jdk 1.6.0_45.

1. You have to define compatible versions of Progurad maven plugin and Progurad base plugin.

2. It is possible to set Classes are not to obfuscate. (Public Classes are set as non obfuscate since that classes act as entry point to the Services)

 

Progurad with Maven – Plugin Entry.

Example:- pom.xml


<plugin>
            <groupId>com.github.wvengen</groupId>
            <artifactId>proguard-maven-plugin</artifactId>
            <version>2.0.6</version>
            <dependencies>
                <dependency>
                    <groupId>net.sf.proguard</groupId>
                    <artifactId>proguard-base</artifactId>
                    <version>4.10</version>
                </dependency>
            </dependencies>
            <executions>
               <execution>
                   <phase>package</phase>
                   <goals><goal>proguard</goal></goals>
               </execution>
            </executions>
            <configuration>
                <proguardVersion>4.4</proguardVersion>
                  <obfuscate>true</obfuscate>
                <options>
		<!-- Keep public classes non obfuscate mode-->
              <option>-keep public class * { public protected *; }</option> 
      		</options>
                <libs>
                    <lib>${JAVA_HOME}/jre/lib/rt.jar</lib>
                    <lib>${JAVA_HOME}/jre/lib/jce.jar</lib>
                </libs>
            </configuration>
        </plugin> 

 

 

 

Tagged with: , , , , , , ,
Posted in Obfuscation

Test Driven Development

TDD_Life_Cycle

Posted in Uncategorized

Embedded jetty with Cuubez

In this tutorial, we show you how to develop a simple RESTfull web service application with embedded jetty server using cuubez framwork.

Technologies and Tools used in this article:

  1. cuubez 1.1.1
  2. JDK 1.7
  3. Maven 3.0.3
  4. Intellij IDEA 13.1.1

Note: If you want to know what and how REST works, just search on Google, ton of available resources.

1. Directory Structure

This is the final web project structure of this tutorial

jetty-package

2. Standard Java Project

Create a standard Maven java project structure.

mvn archetype:generate -DgroupId=com.cuubez -DartifactId=cuubez-jetty -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

3. Project Dependencies

Following maven dependencies should add to the pom.xml file.

File : pom.xml

<dependency>
  <groupId>com.cuubez</groupId>
  <artifactId>cuubez-core</artifactId>
  <version>1.1.1</version>
</dependency>

<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-servlet</artifactId>
  <version>8.0.4.v20111024</version>
</dependency>

 

 

4. REST Service

 

@Path("/users/{userId}")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    private static Log log = LogFactory.getLog(UserResource.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response userGet(@PathParam(value = "userId") String id, @QueryParam(value = "name") String name, @QueryParam(value = "age") int age) {

        User user = new User(id, age, name);
        return Response.ok().entity(user).build();
    }

    @Consumes(MediaType.APPLICATION_JSON)
    @POST
    public void userPost(User user) {
        log.info("POST = [" + user + "]");
    }

    @PUT
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public void userPut(User user) {
        log.info("PUT = [" + user + "]");

    }

}

 

5. Embedded Jetty Implementation

public class JettyServer {

    public static void main(String args[]) {

        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        server.setHandler(handler);
        handler.setContextPath("/");
        handler.setResourceBase(".");
        handler.addEventListener(new BootstrapContextListener());  //cuubez bootstrap context listner
        handler.addServlet(HttpServletDispatcher.class, "/rest/*"); //servlet filter

        try {

            server.start();
            server.join();

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

    }
}

 

6. Demo

In this example, web request from projectURL/rest/users/id-1003 will match to UserResource, via @Path(“/users/{userId}”). {userId} will match to parameter annotated with @PathParam and age and name will match to parameters annotated with @QueryParam.

URL : http://localhost:8080/rest/users/id-1003?name=jhone&age=30

jetty-demo

 

Download this example – cuubez-jetty.zip

Posted in Uncategorized

Mocking Final Classes with Mockito

I have used PowerMock with Mockito for mocking final Class.

Following are Maven dependencies for PowerMock and Mockito.
Eg. pom.xml

<dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>1.5.5</version>
 	 <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>1.5.5</version>
     
      <scope>test</scope>
  </dependency>

Scenario

We have final class called TestFinal.java with public method called Send(String parameter).
Need to mock Send method.

How we do that?

Eg: Final Class is as follows

final class TestFinal{

       public String send(String input){

       //method to process the input
       String status=Processor.getResult(input);

       return status;

     }

}


Mocking send method


import java.io.IOException;
import java.util.HashMap;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;



@RunWith(PowerMockRunner.class)
@PrepareForTest(TestFinal.class)
public class RequestFlowTest {

   
   
    @Test
    public void shouldTestRequestData() throws Exception {
 
 	TestFinal testFinal = PowerMockito.mock(TestFinal.class);
        PowerMockito.when(testFinal.send("testInput")).thenReturn("Success");

 	String result=testFinal.send("testInput");

	org.junit.Assert.assertEquals"Success",result);

 
    }
    
    
   } 
Tagged with: , , , , , ,
Posted in Uncategorized

REST Web Application with Cuubez

In this tutorial, we show you how to develop a simple REST web application with Cuubez.

Technologies and Tools used in this article:

1.Cuubez 1.0.0
2.JDK 1.6
3.Tomcat 6.0
4.Maven 3.0.3
5.Intellij IDEA 13.1.1

Note If you want to know what and how REST works, just search on Google, ton of available resources.

 

 

Screenshot1

 

 

2. Standard Web Project
Create a standard Maven web project structure.

 

mvn archetype:generate -DgroupId=com.cuubez -DartifactId=Employee-example
        -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Note To support IDEA, use Maven command :

mvn idea:idea

3. Project Dependencies
The recommended way to get started using cuubez-framework in your project is with a dependency management system – the snippet below can be copied and pasted into your build(pom.xml). Need help? See our getting started guides on building with Maven.

 

File : pom.xml



<dependencies>
   <dependency>
     <groupId>com.cuubez</groupId>
     <artifactId>cuubez-core</artifactId>
     <version>1.0.0</version>
   </dependency>
</dependencies>

4. REST Service

Simple REST service with Cuubez

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import com.cuubez.example.entity.Employee;

@Path("/employees")
public class EmployeeResource {

    @Path("/{empId}")
    @GET
    public Employee getEmployee(@PathParam("empId") final String empId) {

        Employee employee = new Employee(empId, "jhon powel", "marketing", "No 321, Colombo 4", "+94775993720");
        return employee;
    }
}

5. web.xml
The ContextLoaderListner context listener has to be deployed in order to create the registry for cuubez ,while the ServiceInitiator servlet is used so that incoming requests are correctly routed to the appropriate services. We have configured the specific servlet, named cuubez, to intercept requests under the /rest/ path.

 

File : web.xml

 

<web-app>
  <display-name>Employee Example</display-name>

    <listener>
        <listener-class>com.cuubez.core.servlet.BootstrapContextListener</listener-class>
    </listener>

    <servlet-mapping>
     <servlet-name>init</servlet-name>
     <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <servlet>
     <servlet-name>init</servlet-name>
     <servlet-class>com.cuubez.core.servlet.HttpServletDispatcher</servlet-class>
    </servlet>

</web-app>

6. Demo

In this example, web request from projectURL/rest/employees will match to EmployeeResource, via @Path(“/employees”). And the {empId}from projectURL/rest/employees/{empId} will match to parameter annotated with @PathParam.
URL :  http://localhost:8080/employee-example-1.0.0/rest/employees/eId-0001_

Screenshot2

 

 

Download above Employee example –Employee-example.zip

Tagged with: , , , , , , , ,
Posted in Uncategorized

Spring AOP

Introduction
Spring Framework contains built-in AOP infrastructure.
It is defined in org.springframework.aop.* packages.
Following are the explanations of the Vocabulary which plays around AOP.
This will help you to understand basic concepts around AOP.

Aspect
Think of this as the general feature you want to apply globally to your application
(logging, performance monitoring, exception handling, transaction management, etc).

Advice

A chunk of code that is invoked during program execution,
and is a piece of the logic for implementing your aspect.
This is the first important piece of a Spring AOP aspect implementation

Joinpoint
A *single* location in the code where an advice should be executed (such as field access, method invocation , constructor invocation, etc.).
Spring’s built-in AOP only supports method invocation currently.

Pointcut
A pointcut is a set of many joinpoints where an advice should be executed.
So if, in Spring, a joinpoint is always a method invocation, then a pointcut is just a set of methods that, when called, should have advices invoked around them.
This is the second important pieces of a Spring AOP aspect implementation!

Targets/Target Objects
The objects you want to apply an aspect or set of aspects to

Introduction

This is the ability to add methods to an object.
This is closely tied to, and is almost analogous to the term ‘mixins’.
It’s really just a way to make an object of type A also an object of type B.
Introduction in Spring is limited to interfaces.

Tagged with: , , , , ,
Posted in Uncategorized