Feb 27, 2012

Encrypt/Decrypt Properties using PropertyPlaceholderConfigurer

Spring allows for configuring context bean properties by directly injecting property values from properties file through PropertyPlaceholderConfigurer. At high level this is how it is configured

In the context, you will need to configure a property-placeholder with location poitning to the required properties file. Then we need to provide the property key for the require bean property .

<context:property-placeholder location="classpath:my.properties"/>
<bean id="myBean" class="MyBeanClass">
<property name="userid"
value=" ${userid} " />
<property name="password" value="${password}" />
</bean>

where my.properties will have
user=myuserid
password=mypassword.

works great.
Now, if I the password is encrypted in the properties file and needs to be decrypt it before setting it as the bean property.

There are various approaches to doing it like Over-riding mybean which would decrypt the password during initialization or write a custom ProperOverrideConfigurer to decrypt the property.

There is one another way that can be use, by creating a custom PropertyPlaceholderConfigurer
(extends  PropertyPlaceholderConfigurer  ) and override convert method.

example:

public class DecryptPropertyConfigurer extends PropertyPlaceholderConfigurer
{

@Override
protected void convertProperties(Properties props)
{
Enumeration<?> propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);

String convertedValue = decrypt(propertyValue);
if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
props.setProperty(propertyName, convertedValue);
}
}
}

}

Now, move the properties that need to be decrypted to a new property file
my_encrypted.propeties
password=myencryptedpassword

and configure this property file in the custome PropertyPlaceholder (you will still need to configure the regular property place holder with my.properties)
sothe spring context would look like


<context:property-placeholder location="classpath:my.properties"/>
<bean id="myBean" class="MyBeanClass">
<property name="userid"
value=" ${userid} " />
<property name="password" value="${password}" />
</bean>




<bean class="DecryptPropertyConfigurer">
<property name="location" value="classpath: my_encrypted.propeties"/>
</bean>



1 comment: