Sunday, October 31, 2010

How to list multiple encrypted passwords in properties files

Jasypt is an extremely useful toolkit for encrypting and decrypting passwords. It provides simple instructions for those who want to use Spring and load properties files with encrypted passwords in them.

But, what if you need to provide a whole series of usernames and passwords. How would you accomplish this?
Jasypt's out-of-the-box implementations only read one encrypted value per key=ENC(value) pair in a property file.

Here's a solution:
  1. Override the EncryptablePropertyPlaceholderConfigurer's convertPropertyValue() method. Then you can split a list like the following:
    listOfUsernamePasswords=LIST(username1,ENC(encryptedPassword1),username2,ENC(encryptedPassword2))
    into separate values and only send the encrypted values to the parent convertPropertyValue() implementation to get the decrypted values.
  2. Sew the list back together as a string and return a value that now reads:
    username1,password1,username2,password2
  3. You may be wondering as to who will do the work of breaking up these comma-separated values when they get to your spring bean? The answer is simple: Spring will! For ex: If you had configured you spring bean like so:
    <bean id="someBean" class="com.MyBean">
        <property name="multipleUsernamePasswords" value="${listOfUsernamePasswords}" />
    </bean>
    and the multipleUsernamePasswords property is of type String[] in MyBean class, then StringArrayPropertyEditor will be used implicitly, which will break it up into a string array auto-magically. If you are interested, you can read this blog about how various structures interpret property values for Spring.

  4. Now its up to use that String[] to your advantage in your code.

0 comments:

Post a Comment