Sunday, January 23, 2011

Finished Java 2 unleased. Goodies included

I've finally finished the book of almost a thousand page long! It took me close to 30 hours to finish everything. I think a do learn a great deal more as compared to just doing what work has required me. Even though Java might be a dying program, I still think there is a market for Cheapo peeps like me who feel cost might be the determinant of a successful project continuation.

As of now, there are many people complaining to me how Java is going downhill after Oracle bought over it. I do not have a crystal ball so I would rather not comment. Probably I will learn more about it before jumping to next language, which will be dot Net.

I will be writing my own framework, so that I can improve and showcase my stuff! Below is the helper class to do encryption and decryption for a String. Hope you like it!


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class CipherHelper {
   
    public static final String CIPHER_TYPE = "DES/ECB/PKCS5Padding";
    public static final String KEY_GEN_TYPE = "DES";
   
    public static SecretKey genKey() throws NoSuchAlgorithmException{
        KeyGenerator kg = KeyGenerator.getInstance(KEY_GEN_TYPE);
        return kg.generateKey();
    }
   
    public static byte[] encrypt(String o, SecretKey k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        Cipher cip = Cipher.getInstance(CIPHER_TYPE);
        cip.init(Cipher.ENCRYPT_MODE, k);
       
        return cip.doFinal(o.getBytes());
    }
   
    public static String decrypt(String s, SecretKey k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        Cipher cip = Cipher.getInstance(CIPHER_TYPE);
        cip.init(Cipher.DECRYPT_MODE, k);
        byte input[] = cip.doFinal(s.getBytes());
       
        return new String(input);
    }
}

No comments:

Post a Comment