Friday, October 30, 2009

Encrypt/Decrypt String in Java Property File

Hi all,
I think It would be very useful to know how to encrypt/decrypt a password/general string when we store it in flat file.

In java the common way to store settings properties, like a username or a password,  is to use the Java Property File class using the standard methods:  setProperty, getProperty or  put.  Below a simple example of text file generated from  java:
 username=MyUsername
password=MyPassword
host=myhost

The evident security problem is that password string is readable by everybody, this is not a good thing :) , the solution is to encrypt the password into the file.  We can do it simply with few rows of code.  The follow example explains how encrypting end decrypting string when we are working with Property Files.

We need to write a "helper" class in order to encrypt/decrypt a string through the use of a custom key. In the following  sample the class name is  EncryptionHelper.  In this case we use a source written by Jakelite not by me (PS: thanks Jakelite). You can download it from here.

With the following code I'm writing a property file with the password field encrypted:
 ...
String prefFileName= "config.ini"; //Name of file
Properties prop=new Properties();
FileInputStream file=null;

file =new FileInputStream(prefFileName);
prop.load(file);

EncryptionHelper encryptionHelper; //Class wrote by Jakelite
prop.put("username", "MyUsername");
prop.put("password", encryptionHelper.encrypt(":!MyPassword!:"));
prop.put("host", "myhost");
...

This is the content of generated  file "config.ini":
 username=MyUsername
password=xRS5JsvgsdFv1dFj5HBZVpHhk+FfesDKyXPTAR3hY\=
host=myhost

the rows below show how to read the encrypted password field from property file:
 ...
String prefFileName= "config.ini"; //Name of file
Properties prop=new Properties();
FileInputStream file=null;

file =new FileInputStream(prefFileName);
prop.load(file);

String username;
String password;
String host;

EncryptionHelper encryptionHelper; //Class wrote by Jakelite
username = prop.getProperty("username");
password = encryptionHelper.decrypt( prop.getProperty("password");
host = prop.getProperty("host");
...

I hope I  made myself clear, feel free to comment and/or suggest me everything!

Cheers!

No comments: