Symmetric Encryption
77
// Check the first argument: are we encrypting or decrypting?
if ("-e".equals(args[0])) output = encrypt(password, text);
else if ("-d".equals(args[0])) output = decrypt(password, text);
else usage();
System.out.println(output);
}
private static String encrypt(char[] password, String plaintext)
throws Exception
{
// Begin by creating a random salt of 64 bits (8 bytes)
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
// Create the PBEKeySpec with the given password
PBEKeySpec keySpec = new PBEKeySpec(password);
// Get a SecretKeyFactory for PBEWithSHAAndTwofish
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
// Create our key
SecretKey key = keyFactory.generateSecret(keySpec);
// Now create a parameter spec for our salt and iterations
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
// Create a cipher and initialize it for encrypting
Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
BASE64Encoder encoder = new BASE64Encoder();
String saltString = encoder.encode(salt);
String ciphertextString = encoder.encode(ciphertext);
return saltString+ciphertextString;
}
private static String decrypt(char[] password, String text)
throws Exception
{
// Below we split the text into salt and text strings.
String salt = text.substring(0,12);
String ciphertext = text.substring(12,text.length());
// BASE64Decode the bytes for the salt and the ciphertext