September 2, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Unlocking the Secrets of Java Cryptography Extensions: The Basics

  • October 15, 2008
  • By David Thurmond
  • Send Email »
  • More Articles »

The preceding example is very similar to the previous file encryption example, except for the creation of the key value. The password key is created by using the following snippet of code:

pbeParamSpec = new PBEParameterSpec(salt, count);
char[] password = {'m', 'y', 'b', 'i', 'g', 's', 'e', 'c', 'r',
                   'e', 't'};
pbeKeySpec = new PBEKeySpec(password);
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

In the first three lines, parameters for creating the cipher and password-based key, namely the salt and an iteration count for additional randomness, and of course the password, are specified. Next, a secret key is generated, just as before in the DES encryption examples. Finally, the creation of the password cipher to perform the encryption is done in the following lines:

Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

Note that the password cipher requires not only the key, but also the salt and iteration counter parameters for initialization.

The decryption program, shown in Listing 4.2, is very similar to the encryption example shown earlier. Note that the salt, iteration count, and password are hard-coded in the program, but could easily be entered by the user at the command line or in a dialog.

package com.dlt.developer.crypto;

import javax.crypto.*;
import java.security.spec.*;

import javax.crypto.spec.*;
import java.io.*;

/**
 * @author David Thurmond
 * An example of decrypting a text file using
 * password-based encryption.
 */
public class DecryptFilePasswordExample {
   public static void main(String[] args) throws Exception {

      PBEKeySpec pbeKeySpec;
      PBEParameterSpec pbeParamSpec;
      SecretKeyFactory keyFac;

      // Salt
      byte[] salt = {(byte) 0x9f, (byte) 0x33, (byte) 0x4e,
         (byte) 0xfe, (byte) 0xd4, (byte) 0xee, (byte) 0x12,
         (byte) 0x54};

      // Iteration count
      int count = 17;

      // Create PBE parameter set
      pbeParamSpec = new PBEParameterSpec(salt, count);
      char[] password = {'m', 'y', 'b', 'i', 'g', 's', 'e', 'c',
                         'r', 'e', 't'};

      pbeKeySpec = new PBEKeySpec(password);
      keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
      SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

      // Create PBE Cipher
      Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

      // Initialize PBE Cipher with key and parameters
      pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
      System.out.println("Encrypting file using DES/ECB/PKCS5Padding");

      System.out.println("Reading encrypted file and decrypting...");
      BufferedOutputStream outData =
         new BufferedOutputStream(new FileOutputStream
         ("password_decrypted_data.txt"));
      BufferedInputStream in =
         new BufferedInputStream(new FileInputStream
         ("password_encrypted_data.txt"));
      while (in.available() > 0) {
         // Read the next chunk of bytes...
         byte[] cleartextBytes = new byte[in.available()];
         in.read(cleartextBytes);
         // Now, encrypt them and write them to the encrypted file...
         byte[] encryptedBytes = pbeCipher.update(cleartextBytes);
         outData.write(encryptedBytes, 0, encryptedBytes.length);
      }    // while
      // Take care of any pending padding operations
      outData.write(pbeCipher.doFinal());
      in.close();
      outData.flush();
      outData.close();

      System.out.println("Done!");
   }    // main

}

Listing 4.2: DecriptFilePasswordExample.java

Above, the password cipher parameters and password key are initialized as in the encryption program, and the Cipher object is initialized in decryption mode with the key and parameters. The process takes the password_encrypted_data.txt file and decrypts it by using the Cipher object, writing the output to password_decrypted_data.txt. Note that, as before, the Cipher.update() and Cipher.doFinal() methods are used to encrypt and decrypt blocks of data from the input files.

Conclusion

Cryptography is the process of taking human-readable text and converting it to unreadable text and back again. Here, you have learned how to perform encryption using the Java Cryptography Extensions, and how to install and use third-party cryptography libraries. By using the techniques discussed here, you now have the tools to provide security for any enterprise's most important asset: its data.

Download the Code

You can download the code that accompanies this article here.

References

About the Author

David Thurmond is a Sun Certified Developer with over fifteen years of software development experience. He has worked in the agriculture, construction equipment, financial, home improvement, and logistics industries.





Page 6 of 6



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel