Sunday, June 3, 2012

Encryption Decryption in JAVA based on Password Based Encryption (PBE) 

   Following program String encryption/decryption done by using AES2 and MD5 algorithm.

public class Encryption {
 

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        Encryption e = new Encryption();
        String pwd = "password";
        String salt = "1234";
        String pwdsalt = pwd.concat(salt);
        String enc = e.Encrypt("This is sample test", pwd, salt);
        System.out.println("Encryption String :"+enc);
        String dec = e.Decrypt(enc, pwd, salt);
        System.out.println("Encryption String :"+dec);
        // TODO code application logic here
    }

    String Decrypt(String text, String pwd, String salt) throws Exception {
        String key = pwd + salt;
        Cipher cipher = Cipher.getInstance("AES");
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        MessageDigest digest = MessageDigest.getInstance("MD5");
         digest.reset();
         byte[] md5PwdBytes = digest.digest(keyBytes);
        SecretKeySpec keySpec = new SecretKeySpec(md5PwdBytes, "AES");
        //IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        BASE64Decoder decoder = new BASE64Decoder();
//        NodeList list = doc.getElementsByTagNameNS(
//                    EncryptionConstants.EncryptionSpecNS,
//                    EncryptionConstants._TAG_ENCRYPTEDDATA);
        byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
        return new String(results, "UTF-8");
    }

    String Encrypt(String text, String pwd, String salt)
            throws Exception {
        String key = pwd+salt;
        Cipher cipher = Cipher.getInstance("AES");
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        MessageDigest digest = MessageDigest.getInstance("MD5");
         digest.reset();
         byte[] md5PwdBytes = digest.digest(keyBytes);
        SecretKeySpec keySpec = new SecretKeySpec(md5PwdBytes, "AES");
        //IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);

        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(results);
    }
    
    
}