Tuesday, October 30, 2012

Encrypting Properties File Values with Jasypt

Encrypting Properties File
Values With Jasypt


What's the fuzz all about?

Property files are text resources in your standard web application that contains key-value information. There may come a time when information should not be stored in plain sight. This article will demonstrate how to encrypt properties file values using Jasypt encryption module. Jasypt is freely available and comes with Spring Framework integration.


Library Versions:
  • Spring 3.1+
  • Jasypt 1.9.0

A standard java web-based application may consist numerous properties file. An example of those files would be:
  • application.properties
  • jdbc.properties
  • mail.properties
  • amazon.properties
As an example for a file like mail.properties it would contain key-value pairs used by the application to configure a web-application at different stages of the running web application.

Plain Text Values In Properties Files

local.mail.smtps.password=Take the blue pill

As you can see sensitive information like the username and password is stored in plain text. To make it even worst, we check this in to a source repository like github.

Wouldn't it be nice if we could encrypt username and password values?

Encrypted Values In Properties File

With Jasypt you can enter encrypted values by enclosing them with ENC('value'). The values are decrypted in-memory (i.e. during load-time) using a Jasypt-based extension of Spring Framework's org.springframework.context.support.PropertySourcesPlaceholderConfigurer.

SEE mail.properties

This is how it's done.

Standard Property Placeholder Syntax

Spring XML Config:
<context:property-placeholder location="classpath*:*.properties"/>

Use Jasypt's EncryptablePropertySourcesPlaceholderConfigurer

Spring XML Config:
<bean id="textEncryptor" class="org.jasypt.util.text.BasicTextEncryptor" p:password="go-big-or-go-home"/>
<bean id="propertyPlaceholder" class="org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer"
p:locations="classpath*:*.properties" c:textEncryptor-ref="textEncryptor"/>

You may want to vary your configuration for each environment. For instance dev would be just the default Spring PropertySourcesPlaceholderConfigurer and stage, prod would use Jasypt's EncryptablePropertySourcesPlaceholderConfigurer. One would use Spring Framework Profile Feature (or equivalent) to vary configurations between deployment but this type of discussion is beyond the scope of this blog.

Example Usage: Mail Sender Bean Config
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:protocol="smtps"p:host="${mail.smtps.host}" p:port="${mail.smtps.port}"
p:username="${mail.smtps.username}" p:password="${mail.smtps.password}"/>

Example Usage: Spring Configured
public class MailController {

private String email;
private String password;


SEE app-ctx.xml

Generating Salted Encrypted Values

I created an example of how you would produce an encrypted value using a JUnit test class.
package com.lagnada.xmx1024.integration;

import org.jasypt.util.text.BasicTextEncryptor;
import org.junit.Before;
import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

* Test Utility for generating encrypted passwords for {@link org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer}
public class TextEncryptorTest {

BasicTextEncryptor encryptor;

public void setUp() throws Exception {
encryptor = new BasicTextEncryptor();

public void generateEncryptedText() {
String plainText = "Take the blue pill";
String encrypted = encryptor.encrypt(plainText);
System.out.printf("encrypted: %s%n", encrypted);

You can then use this value and enclose it with ENC() in any of your sourced properties file.


*Note that each time you run the test it will produce a different encrypted text value because it is salted

SEE TextEncryptorTest.java


The entire source code can be pulled at github xmx1024. Please feel free to fork it.


What is Jasypt?

Monday, October 29, 2012

Secure SMTP with Spring JavaMailSender


Like many cost-effective individuals out there I migrated most of my email service which I was paying approximately $50/year for to use Google Apps For Your Domain. This is a free service that in fact I am very satisfied with. But using the smtp service with the Spring JavaMailSender on my old email account was straight forward. The problem I now have is that Google Apps For Your Domain uses the smtps protocol to send emails and because I was using an older version of Java Mail (1.3) I could not programmatically send emails using the secure smtp protocol. In addition to that, the default implemation of JavaMailSender (JavaMailSenderImpl.java) in Spring Framework currently does not have the ability to smoothly handle sending messages using the secure smtp (smtps) protocol.

I stumbled into this when developing a web application that requires an SMTP account to send test emails and other email notifications to the users of this application. Not having the luxury to run my own SMTP server I decided that I would just temporarily use a Gmail (TM) account for sending the messages during development. It just so happens that Gmail uses Secure SMTP to send email messages and on top of that it requires the user to authenticate.

Java Libraries You Will Need

In further investigating this issue it turns out that pre Java Mail 1.4, there is no support for SMTPS Protocol. So we need to download the latest version at Java Mail.
  • Option #1:

    Download the latest Java Mail API jars.
    When using this route be warned that on the final click to download the java mail product you will be re-routed to install the Sun(TM) Download Manager. I am just really puzzled why Sun(TM) has the need to create their own download managers.

  • Option #2:

    Download the latest
    Java Platform Enterprise
    and use the mail.jar that came with that product.

The particular class file that you want to check for in these jars are: com.sun.mail.smtp.SMTPSSLTransport.
Please note that for either options you will still need the Java Activation Framework (activation.jar).

JavaMailSenderImpl with Secure SMTP/SMTPS Support

In my own extension of the the JavaMailSenderImpl.java (see Source Code), it will automatically set the protocol to smtps and add Java Mail smtps properties if the property smtp.isSecure is set to true. Basically, the properties smtp host, username, password, and port will be required.  Also note the property smtp.isSecure is not a Java Mail property. It is just the property name that I came up with so that the code can toggle between normal smtp and smtps protocol.

I also created an override for the super.doSend(..) method so that after calling the Transport.connect(..) method, it will test for connection via the Transport.isConnected() method. This is just an extra step to make sure that we are connected to the SMTPS server and may not be needed in some cases.

Futhermore, If you have a CRUD for the server configuration,  the mail.properties value may be replaced with an implementation that retrieves its values from the database as well.


The solution below now works using Spring 3.x version and Java Mail 1.4.5. The following Spring config is all you need to enable smtps.
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:protocol="smtps" p:host="smtp.gmail.com" p:port="465"
p:username="morpheus@gmail.com" p:password="take-the-blue-pill" />

Friday, April 27, 2012

Pitaka Password Wallet App

Pitaka which also means "Wallet" is a secure password wallet personal storage manager Android(TM) application. You can store sensitive information about your credit card, bank account, email, web credentials, locker combinations, birthdays, etc.
If you feel overwhelmed with all the logons you have to remember this application is for you. Never forget your sensitive information again. Your information is stored securely using the strongest and most Advanced Encryption Standard (AES 256-bit).

Nursing Homes App

Nursing Homes enables you to find the nursing homes throughout the United States and in your area. 
Deciding between nursing homes takes research and a basic understanding of differences among providers. Let the Nursing Homes app be your aid in finding the right care facility for your loved ones.
This application is a great resource for anyone looking for care for a loved one or for caregivers looking for areas of opportunities.
  • Nursing Homes search in your area
  • Nursing Homes throughout the United States
  • Find vital information regarding the Nursing Homes in your area

Decoupling Domain Objects


Given a top down design where the domain objects do not match the entity objects, one of the common techniques in object oriented design is to decouple the object layers. One decoupling technique is to use composite objects. Each level of abstraction will utilize its own composite object (Domain and View). It seems like a lot to write from the looks of it but most IDE supports creations of delegate methods now anyways.


Service Layer, Persistent Object, Domain Object, View Object

Service Layer

public interface BlogManager {
    Blog load(String name) throws EntityNotFoundException;

public class BlogManagerImpl implements BlogManager {
    // Fictitious EntityManager
    EntityManager em;

    public Blog load(String name) throws EntityNotFoundException {
        Blog blog = null;
        BlogData data = em.query("select b from BlogData b where b.name = ?", name);
        return new Blog(data);

Persistent Object

BlogData: an entity-managed persistent object (managed by hibernate for example)
public class BlogData {

   private String name;

   public String getName() {
      return name;

   public void setName(String name) {
      this.name = name;


Blog (First-class citizen)
public class Blog {
    private BlogData delegate;

    public Blog(BlogData delegate) {
        this.delegate = delegate;

    // Example delegate methods
    public getName() {
        return delegate.getName();

    public BlogData getData() {
        return delegate;

View Object

public class BlogBean {

    private Blog delegate;

    public BlogBean(Blog delegate) {
        this.delegate = delegate;

    public String getName() {
        return delegate.getName();

    // custom UI method

    public boolean isActive() {
        // custom code (UI Logic)

Example Controller

public class BlogController {

    public void getBlog(String name) {
        ModelMap model = new ModelMap();
        BlogBean blog = blogManager.load(name);
        model.addAttribute("blog", blog);


Thursday, September 10, 2009

Binding Tabular Data with SpringFormControllers

This blog discusses the nature of dynamic tabular data in web applications and how this is handled in Spring Framework. The main point here is that the tabular data cannot be modified in any way or else an IndexOutOfBoundsException will occur.

Assume for a moment that we have tabular data we want to edit the quantity on our cart items. The tabular field is indexed using open and closing square brackets [].

<c:forEach var="item" items="${shoppingCartForm.items}" varStatus="s">
    <spring:bind path="shoppingCart.items[${s.count-1}].quantity">
    <input type="text" name="${status.expression}" value="${status.value}"
        style="width: 100%;"/>

The formBackingObject() method

Override SimpleFormController's formBackingObject() method in your form controller class:

protected Object formBackingObject(HttpServletRequest request) throws Exception {
    Long cartId = RequestUtils.getRequiredLongParameter(request, "cartId");
    ShoppingCart cart = shoppingCartManager.findShoppingCart(cartId);
    return new ShoppingCartCommand(cart);

The Detailed Explanation

When spring binds the array it expects items to have contents. Therefore, we need to override the SimpleFormController.formBackingObject to always retrieve the current data.

During the form rendering (showForm()) our page is rendered and the moment the Controller processes the request after the form is submitted, the controller will retrieve the most current data via the SimpleFormController.formBackingObject().

If for some reason the shopping cart items increased (via some method in the JSP) the binding will throw an IndexOutOfBoundsException because the items currently in our database will be less than what we are trying to bind.

If we have this situation we need to explicitly correlate the number of items to be persisted with the ShoppingCartCommand.items to avoid the exception.

Number of items from the database: 3
The user added another item which totals to 4

In the SimpleFormController.formBackingObject() method we need to figure out how many new items were added and increase the list size so the binding can occur. In our case we need to increase the list size by 1.

Monday, January 12, 2009

Spring Acegi: Force Re-Authenticating Other Users When Roles Change

Here's the Scenario that I have an issue with:

A System Administrator edits a user role and the user whose role is currently logged in could possibly already be logged in.

When System Administrators log into a website and edit a user role, the default implementation of Spring Acegi does not re-authenticate the user if the user is currently logged in to the system. In short, if the user in question is an administrator and you remove the admin role from the user the changes doesn't take effect until the next time this user re-authenticates--i.e. log-out then log back in.

The Solution:

The ideal solution would be for the system without turning on the alwaysReauthenticate to detect that the user information has changed and will automatically re-authenticate user in question is already logged in to the system.

How do I get acegi to re-authenticate the user who is currently logged in whenever this person's user roles are edited? I don't want to turn on alwaysReauthenticate property on the FilterSecurityInterceptor. The solution I came up with is whenever the EditUserFormController executes (only executed by admins) to save the user information (including but not limited to user roles), I clear the userCache entry for that user and added a filter that will check whether the user exists in the userCache. If it doesn't it will set the Authentication.authenticated property to false, hence to be forced to re-authenticate in FilterSecurityInterceptor. This filter executes before the FilterSecurityInterceptor in the filter chain.

This seems to work fine but without turning on the alwaysReauthenticate property this is the most perfomance-saavy solution until a functionality like this (if it makes sense to implement) is implemented in Spring Acegi.

Here's the code snippet from the filter I created:
protected void reAuthenticateAsNeeded() {
   Authentication authentication = SecurityContextHolder.getContext()
   if (!("anonymous".equalsIgnoreCase(authentication.getName()))
           && authentication.isAuthenticated()
           && m_userCache.getUserFromCache(authentication.getName()) == null) {

Please note that the following FilterSecurityInterceptor is then executed and will re-authenticate the user. (see also AbstractSecurityInterceptor#beforeInvocation())