Chapter 4
70
To run the example, enter the following:
C:\> javac SimpleExample.java
C:\> java SimpleExample "HelloWorld!"
The string "HelloWorld!" will then be converted to a byte array, encrypted, and then decrypted and
converted back to a String. Here's what the output should look like bearing in mind that the actual
ciphertext will be different each time you run the example, because the key is generated anew on every
execution:
Generating a DESede key...
Done generating the key.
Plaintext:
72 101 108 108 111 87 111 114 108 100 33
Ciphertext:
78 78 -43 -52 -12 -87 112 -68 24 -16 -49 -88 101 -44 -66 122
Decrypted text: HelloWorld!
Blowfish Example
Now we're going to modify the previous example to use Blowfish instead of DESede. Thanks to the
architecture of the JCE, this is a very simple task. We just change the arguments passed to the
KeyGenerator and Cipher initializations, and a few comments. Blowfish keys can be any bit size from 8
to 448, as long as the number is divisible by 8. We'll use 128 for our example.
The changes from the DESede example are highlighted below:
import java.security.*;
import javax.crypto.*;
/**
* BlowfishExample.java
*
* This class creates a Blowfish key, encrypts some text,
* prints the ciphertext, then decrypts the text and
* prints that.
*
* It requires a JCE-compliant Blowfish engine.
*/
public class BlowfishExample
{
public static void main (String[] args)
throws Exception
{
if (args.length != 1) {
System.err.println("Usage: java BlowfishExample text");
System.exit(1);
}
String text = args[0];
System.out.println("Generating a Blowfish key...");
// Create a Blowfish key