Sep 29, 2012

Data Encryption in Java Part 1

Blowfish Cipher Cryptography
In this example, I will show you how to encrypt data in Java using Blowfish Cipher algorithm. Blowfish is a keyed, symmetric block cipher, with 64-bit block sized encryption algorithm, with a variable key length from 32 bits up to 448 bits. Blowfish provides a good encryption rate in software. It is meant to be an alternative to DES(Data Encryption Standard) which is the predominantly used algorithm for the data encryption developed at IBM in the early 1970s.

 I used a simple text input to be encrypted which is later being decrypted back to its original form. The generated key is based on the Blowfish algorithm and needed for the both two operations. The data is being converted to array of bytes before it is encrypted.
package codecypherprojects;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Khamis
 * 
 */

public class DataEncryption {
    
    private static String cipher_key = "Blowfish";
    private static Cipher cipher;
    private static KeyGenerator k_generator;
    private static SecretKey secret_key;
    
    public static void main(String args[]) throws NoSuchAlgorithmException{
        try {
            execute_data_encryption();
        } catch (InvalidKeyException ex) {
            System.out.println("Error! " + ex.getMessage());
        }
    }

    private static byte[] decrypt_data(byte[] encrypted_text) 
            throws InvalidKeyException {
        byte[] decrypted = null;
        try {
            //Initialize cipher with the generated secret key
            cipher.init(Cipher.DECRYPT_MODE, secret_key);
            
            //Do the decryption
            decrypted = cipher.doFinal(encrypted_text);
           
        } catch (IllegalBlockSizeException | BadPaddingException ex) {
            System.out.println("Error! " + ex.getMessage());
        }
         return decrypted;
    }


    private static byte[] encrypt_data(String plain_text) 
            throws InvalidKeyException {
         byte[] encrypted = null;
        try {
            //Re-initialize the cipher  for decription
            cipher.init(Cipher.ENCRYPT_MODE, secret_key);
            
            //Do the encryption
            encrypted = cipher.doFinal(plain_text.getBytes());
            
        } catch (IllegalBlockSizeException | BadPaddingException ex) {
            System.out.println("Error! " + ex.getMessage());
        }
        return encrypted;
    }

    private static void execute_data_encryption() 
            throws NoSuchAlgorithmException, InvalidKeyException {
               try {
            //Generate encryption key based on codecypherkey code word
            k_generator = KeyGenerator.getInstance(cipher_key);
            
            //Create a secret key
            secret_key = k_generator.generateKey();
            
            //Create Cipher based on the previous encryption key code
            cipher = Cipher.getInstance(cipher_key);
            
            //Pass the data to be encrypted. in this case a simple string
            String plain_text = JOptionPane.showInputDialog(
                    "Type in the text to be encrypted");
                    
            
            //Encrypt the text and store the data as bytes array             
            byte[] encrypted_data = encrypt_data(plain_text);
            
            //Decrypt the the text back to its original form as bytes
            byte[] decrypted_data = decrypt_data(encrypted_data);
            
            //Show dialog with the result summary 
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), 
                    "The encrypted data is: "
                    + new String(encrypted_data) + "\n" + "Dectrypted data is : " 
                    + new String(decrypted_data),
                    "Encryption Summary",  JOptionPane.PLAIN_MESSAGE);
            
            System.exit(0);
           
           
        } catch (NoSuchPaddingException ex) {
            System.out.println("Error! " + ex.getMessage());
        }
    }
}

Related Posts 

 

Data Encryption in Java Part 2

 

4 comments:

  1. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

    ReplyDelete
  2. Thanks for post! ;) I've one more implementations of blowfish for Java - http://dexxtr.com/post/57145943236/blowfish-encrypt-and-decrypt-in-java-android - what do you think?

    ReplyDelete
  3. Can we execute this mechanism to encrypt image files using java ?

    ReplyDelete
    Replies
    1. We are dealing with raw bytes here, so it can be applied to images as well. You may need more code for that though.

      Delete