Tuesday, September 25, 2012

Encryption and Decryption in Java

I had already written a post on the same earlier. But it works only when pass the encrypted value to the decryptor method before the SecretKey is generated again. This is because, each time we call to generate the SecretKey, it generates a new one each time.

I have found a solution to this. This comes handy when you are encrypting the data and storing it somewhere and later want to retrieve the data and decrypt it while doing so. This can be done using the 'AES' algorithm instead of the 'DES' used in the previous example.

The AES algorithm, generates the same SecretKey each time you generate it. Here is the implementation :

 private static final String ALGO = "AES";
        private static final byte[] keyValue =
            new byte[] { 'm', 'a', 'n', 'a', 's', 'w', 'i','t', 'a', '_', 'm','i', 's', 'h', 'r', 'a' };

/**
     * Encrypt the password before saving   
     * @param Data
     * @return
     * @throws Exception
     */
    public static String encrypt(String Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    /**
     * Decrypt the password before recieving
     * @param encryptedData
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }
    /**
     * Key Generator for encryption and decryption
     * @return
     * @throws Exception
     */
    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
}

Here is a simple client to test the implementation above

public static void main(String[] args) throws Exception {
        String password = "password";
        String passwordEnc = AESencrp.encrypt(password);
        String passwordDec = AESencrp.decrypt(passwordEnc);

        // This key generates the same value each time you run it
        System.out.println(generateKey());

        System.out.println("Original password : " + password);
        System.out.println("Encrypted password: " + passwordEnc);
        System.out.println("Decrypted password: " + passwordDec);
    }

No comments: