How to Encrypt Spring Datasource Password Credentials

 Posted On  | Yashwant Chavan | Views :- 5143

Its a bad programming practice to display credentials in the spring data-source configuration file. In this article we are going to use the Encrypted password with the help wrapper data-source class.

Lets follow the below steps to create sample Spring + hibernate application which use the Encrypted password to get the database connection. Spring framework provides the facility to extend the DriverManagerDataSource class and creates the custom class.

Useful to whom

This tutorial is useful for beginners and experience developers. It will helps you to learn step by step with the help of attached code.

Tools and Technologies

To execute sample Spring Hibernate program we use below technologies

  1. Maven 3.0.4
  2. JDK 1.6
  3. Hibernate 3.2.6.ga
  4. Spring 2.5.6
  5. MySql 5.1

Maven dependancy pom.xml

Define Spring and Hibernate Dependencies in pom.xml, In this tutorial simply insert the record into employee table.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.technicalkeeda.hibernate</groupId>
	<artifactId>com.technicalkeeda.hibernate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>HibernateExamples</name>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.2.6.ga</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.3.1.GA</version>
		</dependency>

		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>

		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm</artifactId>
			<version>3.1</version>
		</dependency>

		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
                </dependency>
	</dependencies>
	<build>
		<finalName>HibernateExamples</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Custom Spring Datasource (EncryptedDataSource.java)

I have written a wrapper class EncryptedDataSource for org.springframework.jdbc.datasource.DriverManagerDataSource and overridden getPassword() method. EncryptedDataSource class is injected in spring datasource configuration xml file. Which calls the overriden getPassword() method of data-source at the time of database connection. getPassword() method decode the encrypted password into actual password. To decrypt or encrypt password we used "BASE64Decoder" algorithm.

package com.technicalkeeda.dao.utility;

import java.io.IOException;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import sun.misc.BASE64Decoder;

public class EncryptedDataSource extends DriverManagerDataSource {

	@Override
	public String getPassword() {
		String password = super.getPassword();
		return decode(password);
	}

	/***
	 * Decode Password
	 */
	private String decode(String decode) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			decode = new String(decoder.decodeBuffer(decode));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return decode;
	}

}

Spring Datasource Configuration (spring-configuration.xml)

Bean datasource is define with custom EncryptedDataSource class , rather than DriverManagerDataSource class. Here I have passed the encrypted password to the spring data-source. <property name="password"><value>cGFzc3dvcmQ=</value></property>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- This is Database Configuration -->
	<bean id="dataSource" class="com.technicalkeeda.dao.utility.EncryptedDataSource">
		<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
		<property name="url"><value>jdbc:mysql://localhost:3306/technicalkeeda</value></property>
		<property name="username"><value>demo</value></property>
		<property name="password"><value>cGFzc3dvcmQ=</value></property>
	</bean>

	<bean id="employeeDao" class="com.technicalkeeda.dao.impl.EmployeeDaoImpl">
		<property name="sessionFactory" ref="hibernateSessionFactory" />
	</bean>

	<bean id="hibernateSessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.technicalkeeda.entities.Employee</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
			</props>
		</property>
	</bean>

</beans>

Hibernate Modal Class (Employee.java)

Create Employee model class with the help of hibernate annotations like @Entity, @Table(name = "trn_employee") and @Column(name = "employee_id")

package com.technicalkeeda.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "trn_employee")
public class Employee {

	@Id
	@GeneratedValue
	@Column(name = "employee_id")
	private long employeeId;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	@Column(name = "email")
	private String email;

	public long getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(long employeeId) {
		this.employeeId = employeeId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

Dao Interface (EmployeeDao.java)

Define a EmployeeDao interface with createEmployee() method. It is going to save the employee entity into trn_employee table.

package com.technicalkeeda.dao;

import com.technicalkeeda.entities.Employee;

public interface EmployeeDao {
	public void createEmployee(Employee employee);
}

Implemention class (EmployeeDaoImpl.java)

EmployeeDaoImpl is the implementation class. Which implements the createEmployee() method.

package com.technicalkeeda.dao.impl;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.technicalkeeda.dao.EmployeeDao;
import com.technicalkeeda.entities.Employee;

public class EmployeeDaoImpl implements EmployeeDao {

	private HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Override
	public void createEmployee(Employee employee) {
		hibernateTemplate.saveOrUpdate(employee);
	}

}

Test Class (App.java)

Build your maven project and execute the App.java class, It is going to create trn_employee table in the database and insert one employee

package com.technicalkeeda.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.technicalkeeda.dao.EmployeeDao;
import com.technicalkeeda.entities.Employee;

public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"config/spring-configuration.xml");

		Employee employee = new Employee();
		employee.setFirstName("Yashwant");
		employee.setLastName("Chavan");
		employee.setEmail("yashwant.*****@gmail.com");

		EmployeeDao employeeDao = (EmployeeDao) appContext.getBean("employeeDao");
		employeeDao.createEmployee(employee);
		
	}
}

Output

When you execute the App.java , output will look like this.

Hibernate: insert into trn_employee (email, first_name, last_name) values (?, ?, ?)

Finish

Hope this Tutorial is useful to you, Please fill free to provide your comments if there is any problem. Thanks

Tags Spring  Spring Datasource  Spring Hibernate  Hibernate 

HTML Comment Box is loading comments...

Hi I am Yashwant Chavan founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.

Latest Updates

Stay updated with latest post, articles and technical discussions.

Most Popular Articles



© technicalkeeda.com 2014