Wednesday, March 23, 2011

Adding encription capability in java applications

Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

http://www.jasypt.org/

Sample code encrypt values - You will need commons-lang-2.3.jar and jasypt-1.6.jar to compile and execute the below program.


import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;

public class MaskPassword
{
    public static void main(String[] args)
    {
        EnvironmentStringPBEConfig conf = new EnvironmentStringPBEConfig();
        conf.setAlgorithm("PBEWithMD5AndDES");
        conf.setPassword("*&^P@ssw0rd*&^W");

        StandardPBEStringEncryptor enc = new StandardPBEStringEncryptor();
        enc.setConfig(conf);

        System.out.println("VLUE_TO_BE_ENCRIPTED Encrypted Value : [" + enc.encrypt("VLUE_TO_BE_ENCRIPTED") + "]");
        System.out.println("nQL5VtGIKhG4mcYg/6U3KJE7Fi7y/SfxsYp7VQIeD54= Decrypted Value : [" + enc.decrypt("toIc7aXUxn6yEHPSWSbYOv7XTbSK8Mjf1OU0JjujV/M=") + "]");
    }
}


Result -
VLUE_TO_BE_ENCRIPTED Encrypted Value : [0PyTACLyIpWoixZmpo7qgBdEkCX41Sw9GgG4gjq8rbQ=]
nQL5VtGIKhG4mcYg/6U3KJE7Fi7y/SfxsYp7VQIeD54= Decrypted Value : [VLUE_TO_BE_ENCRIPTED]


import org.jasypt.util.text.BasicTextEncryptor;

public class MaskPasswordWithBasicTextEncription
{
    public static void main(String[] args)
    {
        String text = "We are using PBEWithMD5AndDES algorithm for encryption";
        System.out.println("Text      = " + text);

        BasicTextEncryptor bte = new BasicTextEncryptor();
        bte.setPassword("*&^P@ssw0rd*&^W");

        String encrypted = bte.encrypt(text);

        System.out.println("Encrypted = " + encrypted);
       
        String original = bte.decrypt(encrypted);
        System.out.println("Original  = " + original);
    }
}

Result -
Text      = We are using PBEWithMD5AndDES algorithm for encryption
Encrypted = X5U1CiNtwaUw/fuXx5FIedALldrW5EUtL9YTQMuwwC4PqpD6bFOuQisc9+lGY3qjnvdKUUAV91owLv3csnSZEw==
Original  = We are using PBEWithMD5AndDES algorithm for encryption



No comments:

Post a Comment