Tuesday, October 7, 2014

Java : File Encryption and Decryption using Blowfish

The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
Source : http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.html

javax.crypto.Cipher
This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
Cipher API : http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html

Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA)
http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

Blowfish  
Blowfish has a 64-bit block size and a variable key length from 1 bit up to 448 bits
Blowfish Wiki : http://en.wikipedia.org/wiki/Blowfish_%28cipher%29

Here are the general steps to encrypt/decrypt a file in Java -

  • Create a Key from a given byte array for a given algorithm.
  • Get an instance of Cipher class for a given algorithm transformation.
  • Initialize the Cipher with an appropriate mode (encrypt or decrypt) and the given Key.
  • Invoke doFinal(input_bytes) method of the Cipher class to perform encryption or decryption on the input_bytes, which returns an encrypted or decrypted byte array.
  • Read an input file to a byte array and write the encrypted/decrypted byte array to an output file accordingly.


Please see the below java code