Symmetric Encryption
89
Running the Application
Now let's run the application. We'll begin by creating a key, protected with the password "sasquatch".
C:\> java FileEncryptor c sasquatch
This will print out a few messages like this:
Generating a Rijndael key
Done generating the key.
Next we can encrypt a file. Create a file called test.txt in your current directory, and place some text in
it. We can then encrypt it to testEncrypted.txt with the following command:
C:\> java FileEncryptor e sasquatch test.txt testEncrypted.txt
This will give the following output:
Loading the key.
Loaded the key.
Initializing SecureRandom...
Initializing the cipher.
Encrypting the file...
You can now view the testEncrypted.txt file to check that it has been encrypted. If we wish, we can
decrypt this file with the following command:
C:\> java FileEncryptor d sasquatch testEncrypted.txt testDecrypted.txt
The output we get from this is:
Loading the key.
Loaded the key.
Initializing the cipher.
Decrypting the file...
We can now view the file testDecrypted.txt to verify that it has been properly decrypted.
CipherStreams with Other Algorithms
There's no requirement that we use Rijndael when encrypting files in the example above. It could easily be
done with any other block cipher without changing anything besides the algorithm name and the bit size of
the key. To use DESede for instance, just change "Rijndael" to "DESede" and the bit size from 256 to 168.
Sometimes we'll want to use a stream cipher, like RC4. RC4 is very fast, and would probably be the best
choice for encrypting extremely large files, like audio or video files. RC4 is not quite as strong as AES, but
as we've mentioned, 128 bits is enough strength for almost any application. Also, if we feel it's necessary,
we can change the keysize we're using for RC4, as it can accept keys of up to 1024 bits.
RC4 doesn't use an initialization vector, as it's built into the algorithm. So we no longer need to create the
IV, store it to the output file, or read it from the input file. There are only two lines that need alterations in
both encrypt() and decrypt(). For encrypt() they are highlighted as shown below: