Symmetric Encryption
85
public static void main (String[] args)
throws Exception
{
if ((args.length < 2) || (args.length > 4))
{
System.err.println("Usage: java CipherStreamExample -c|-e|-d password
[inputfile] [outputfile]");
System.exit(1);
}
// Convert the password into a char array
char[] password = args[1].toCharArray();
if ("-c".equals(args[0])) createKey(password);
else if ("-e".equals(args[0])) encrypt(password, args[2], args[3]);
else if ("-d".equals(args[0])) decrypt(password, args[2], args[3]);
else (System.out.println("Usage: java CipherStreamExample -c|-e|-d password
[inputfile] [outputfile]");
}
Now let's write the createKey() method. The first thing we need to do is generate an AES key. Since
AES is also known as Rijndael, we'll use that as an algorithm name to create a key generator.
/**
* Creates a 256-bit Rijndael key and stores it to
* the filesystem as a KeyStore.
*/
private static void createKey(char[] password)
throws Exception
{
System.out.println("Generating a Rijndael key...");
// Create a Rijndael key
KeyGenerator keyGenerator = KeyGenerator.getInstance("Rijndael");
keyGenerator.init(256);
Key key = keyGenerator.generateKey();
System.out.println("Done generating the key.");
Now we want to encrypt the key with a password. We'll create an 8-byte salt and create a PBE cipher with
the password:
// Prepare key encryption cipher using the password
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(
"PBEWithSHAAndTwofish-CBC");
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATIONS);
Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);