Main()
Now that we have all the required building blocks, the last remaining step is to put it all together. We need to process command line arguments and call the appropriate methods. We also need to add exception handling.
The following main() method is responsible for determining if we are encrypting or decrypting the file and the names of the keys to use:
public static void main(String[] args)
{
boolean encrypt = false;
boolean decrypt = false;
String keyName = null;
/*
* examine all the command line arguments
*/
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("-encrypt"))
{
encrypt = true;
}
else if (args[i].equals("-decrypt"))
{
decrypt = true;
}
else if (args[i].equals("-key"))
{
keyName = args[++i];
}
}
/*
* validate the arguments
*/
if (encrypt == decrypt)
{
if (encrypt)
{
System.err.println("Cannot encrypt and decrypt
file!");
}
else
{
System.err.println("Must specify -encrypt or -
decrypt.");
}
System.exit(1);
}
if (keyName == null)
{
System.err.println("Missing key name.");
System.exit(1);
}
FileCrypt fileCrypt = new FileCrypt();
KeyStore ks = fileCrypt.loadKeyStore();
if (encrypt)
{
PublicKey publicKey = (PublicKey)ks.getKey(keyName,
null);
fileCrypt.encryptFile(System.in, System.out, publicKey);
}
else
{
PrivateKey privateKey = (PrivateKey)ks.getKey(keyName,
null);
fileCrypt.decryptFile(System.in, System.out, privateKey);
}
}