Monday, June 20, 2016

Encryption/Decryption with Java

Following are the steps to encrypt/decrypt with Java
1. determine the encryption key
2. get the keyspec from the encryption key  
3. instantiate the secretkeyfactory
4. generate the secretkey from the keyfactory
5. instantiate the cipher
6. encrypt/decrypt the string into byte array
7. encode to base 64
8. return the encrypted/decrypted string

Sample Code

    public static final String key = "kianworknotes";




    public static String encrypt(String str) {
        try {            
            byte[] keyValue = key.getBytes();

            DESKeySpec desKeySpec = new DESKeySpec(keyValue);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(desKeySpec);

            Cipher ecipher = Cipher.getInstance("DES");
            ecipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] utf8 = str.getBytes("UTF8");
            byte[] enc = ecipher.doFinal(utf8);

            enc = BASE64EncoderStream.encode(enc);
            return new String(enc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String decrypt(String str) {
        try {    
            byte[] keyValue = key.getBytes();

            DESKeySpec desKeySpec = new DESKeySpec(keyValue);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(desKeySpec);

            Cipher dcipher = Cipher.getInstance("DES");
            dcipher.init(Cipher.DECRYPT_MODE, key);

            byte[] dec = BASE64DecoderStream.decode(str.getBytes());
            byte[] utf8 = dcipher.doFinal(dec);

            return new String(utf8, "UTF8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...