Chapter 4
76
Most of the above algorithms are equivalently secure. The only possible exception is PBEWithMD5AndDES.
Since DES uses a 56-bit key, it's possible that a password would be more secure than the DES key it creates.
We recommend using one of the other algorithms if you have a choice in your application.
Unfortunately, no crypto provider supports all PBE algorithms and here we'll use the Bouncy Castle
provider to get support for PBEWithSHAAndTwofish-CBC.
Now let's take a look at our complete example of PBE. It uses SHA-1 and Twofish to encrypt or decrypt
some text using a password. The iteration count is set to 1000 and the salt is randomly chosen on
encryption. The salt is then written to the first 8 bytes of the output text.
PBE Example Code
When decrypting, this program will read the first 8 bytes of the ciphertext and use that as the salt:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
// This is for BASE64 encoding and decoding
import sun.misc.*;
/**
* PBE.java
*/
If you're not using a Sun-based VM, comment out the import sun.misc.* line shown above, and
uncomment the following line. This will switch to our BASE64 encoders:
// import com.isnetworks.base64.*;
public class PBE
{
private static int ITERATIONS = 1000;
private static void usage()
{
System.err.println("Usage: java PBE -e|-d password text");
System.exit(1);
}
public static void main (String[] args)
throws Exception
{
if (args.length != 3) usage();
char[] password = args[1].toCharArray();
String text = args[2];
String output = null;