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
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.