Java - Blowfish Encryption Algorithm

 
BlowfishAlgorithm.java
 
package com.java.blowfish;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
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;

/**
 *
 * @author dhanoopbhaskar
 */
public class BlowfishAlgorithm {

    KeyGenerator keyGenerator = null;
    SecretKey secretKey = null;
    Cipher cipher = null;

    public BlowfishAlgorithm() {
        try {
            /**
             * Create a Blowfish key
             */
            keyGenerator = KeyGenerator.getInstance("Blowfish");
            secretKey = keyGenerator.generateKey();

            /**
             * Create an instance of cipher mentioning the name of algorithm
             *     - Blowfish
             */
            cipher = Cipher.getInstance("Blowfish");
        } catch (NoSuchPaddingException ex) {
            System.out.println(ex);
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex);
        }

    }

    /**
     *
     * @param plainText
     * @return cipherBytes
     */
    public byte[] encryptText(String plainText) {
        byte[] cipherBytes = null;
        try {
            /**
             * Initialize the cipher for encryption
             */
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            /**
             * Convert the text string to byte format
             */
            byte[] plainBytes = plainText.getBytes();
            /**
             * Perform encryption with method doFinal()
             */
            cipherBytes = cipher.doFinal(plainBytes);
        } catch (IllegalBlockSizeException ex) {
            System.out.println(ex);
        } catch (BadPaddingException ex) {
            System.out.println(ex);
        } catch (InvalidKeyException ex) {
            System.out.println(ex);
        }

        return cipherBytes;
    }

    /**
     *
     * @param cipherBytes
     * @return plainText
     */
    public String decryptText(byte[] cipherBytes) {
        String plainText = null;
        try {
            /**
             * Initialize the cipher for decryption
             */
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            /**
             * Perform decryption with method doFinal()
             */
            byte[] plainBytes = cipher.doFinal(cipherBytes);
            /**
             * Convert encrypted text to string format
             */
            plainText = new String(plainBytes);
        } catch (IllegalBlockSizeException ex) {
            System.out.println(ex);
        } catch (BadPaddingException ex) {
            System.out.println(ex);
        } catch (InvalidKeyException ex) {
            System.out.println(ex);
        }

        return plainText;
    }

    /**
     *
     * @param plainText
     * @return cipherText
     */
    public String encrypt(String plainText) {
        String cipherText = null;
        byte[] cipherBytes = encryptText(plainText);
        cipherText = bytesToString(cipherBytes);
        return cipherText;
    }

    /**
     * 
     * @param cipherText
     * @return plainText
     */
    public String decrypt(String cipherText) {
        String plainText = null;
        byte[] cipherBytes = stringToBytes(cipherText);
        plainText = decryptText(cipherBytes);
        return plainText;
    }

    public static void main(String[] args) {
        BlowfishAlgorithm blowfishAlgorithm = new BlowfishAlgorithm();
        String textToEncrypt = "Blowfish Algorithm";
        System.out.println("Text before Encryption: " + textToEncrypt);
        String cipherText = blowfishAlgorithm.encrypt(textToEncrypt);
        System.out.println("Cipher Text: " + cipherText);
        System.out.println("Text after Decryption: " + blowfishAlgorithm.decrypt(cipherText));
    }

    /**
     * 
     * @param rawText
     * @return plainText
     *
     * Perform Base64 encoding
     */
    private String bytesToString(byte[] rawText) {
        String plainText = null;
        plainText = Base64.encode(rawText);
        return plainText;
    }

    /**
     * 
     * @param plainText
     * @return rawText
     *
     * Perform Base64 decoding
     */
    private byte[] stringToBytes(String plainText) {
        byte[] rawText = null;
        try {
            rawText = Base64.decode(plainText);
        } catch (Base64DecodingException ex) {
            System.out.println(ex);
        }
        return rawText;
    }
}

Output: 
Text before Encryption: Blowfish Algorithm 
Cipher Text: tsNKEZdUIivNDDN287v9NIl8vCHTPrlT 
Text after Decryption: Blowfish Algorithm

Post a Comment

11 Comments

  1. my compiler isnt able to import "import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;" this file.

    I'm using jdk 1.6 ...and solution to make the program work.??

    ReplyDelete
    Replies
    1. Hi Lakshya,

      Sorry for the delay in replying. Please try running the program making use of the example command line given below:

      javac -classpath "%CLASSPATH%";C:\Users\dhanoopbhaskar\Desktop\rt.jar BlowfishAlgorithm.java

      - where C:\Users\dhanoopbhaskar\Desktop\rt.jar is the path of the jar file which contains the missing classes (Base64DecodingException, Base64)

      The file rt.jar will be available in your JDK_HOME/jre/lib

      Please let me know in case of errors.

      Thank you.

      Delete
  2. Error: Class blowfish algorithm is is only accepted if Annotation processing is explicitly requested...
    Please solve it asap..

    ReplyDelete
    Replies
    1. Hi,
      I think you have not given ".java" suffix while compiling the program.
      Correct usage:
      javac BlowfishAlgorithm.java

      Delete
  3. Hi Dhanoop I want to use blowfish algo for encrypt a file in one time and use use these encrypted file after some time. on that time i have got a execption "javax.crypto.BadPaddingException: Given final block not properly padded" so what is the procedure to remove these Exception
    please reply me asap..

    ReplyDelete
    Replies
    1. Sorry for being late in replying..

      Please refer my comment in another post: http://www.theinsanetechie.in/2013/08/java-encryption-and-decryption-of-image.html?showComment=1384406568975#c2700803224928338176


      Same key may not be generated in each run of the program. If we need to do that, we have to generate a key from a string value (or password) which the user is providing to the program.

      ---

      Replace the following statements

      keyGenerator = KeyGenerator.getInstance("Blowfish");
      secretKey = keyGenerator.generateKey();

      with

      secretKey = new SecretKeySpec(masterPassword.getBytes(), "Blowfish");
      //import javax.crypto.spec.SecretKeySpec; should be used.

      where masterPassword is the password given.

      Delete
  4. Package com.java.blowfish is written in first line. What do you mean by this? And is that package an open source. If not please provide me the source.. Reply ASAP.. This is a part of my final project...

    ReplyDelete
  5. Package com.java.blowfish is written in first line. What do you mean by this? And is that package an open source. If not please provide me the source.. Reply ASAP.. This is a part of my final project...

    ReplyDelete
    Replies
    1. This was given just for managing various code snippets in the same java project in eclipse (an IDE) which I'm using.
      You may skip it.

      [It directs the compiler that com.java.blowfish is the package (directory -> com/java/blowfish/) in which the class BlowfishAlgorithm is included. Hence the fully qualified classname would be com.java.blowfish.BlowfishAlgorithm]

      Delete
  6. while converting this code into jar i am getting the errorError: Could not find or load main class com.java.blowfish.EncryptFile

    what do i do??

    ReplyDelete
    Replies
    1. Hi,
      Please re-check the steps you followed while creating the jar file.
      The file EncryptFile.class should be inside the package com.java.blowfish.
      In other words, the folder (directory) structure (com/java/blowfish) should be strictly maintained.

      Delete