Java & PGP
One of the Java projects I’m working on required that the application encrypted certain pieces of information (not files, but strings) using PGP, and from what I can tell, there aren’t a whole lot of libraries and/or examples out there. The one I saw mentioned most frequently was the Bouncy Castle Crypto API, but in the short time that I looked through the documentation and the examples (org.bouncycastle.openpgp.examples), I saw nothing that looked like it would help me. So I downloaded PGP 6.5.8 (the version we’ve standardized on at work) from pgpi.org and hacked away at a version that works from the command line. Here’s the result:
String information = "The random text information I want to encrypt.";
String filename = "tempfile.txt";
// path to where I have pgp installed
String directory = "c:\\pgp6.5.8\\";
// my pgp key
String pgpkey = "aaron.s.johnson@gmail.com";
// create a file and write the string to it
File outputfile = new File(directory + filename);
FileWriter out = new FileWriter(outputfile);
out.write(information.toCharArray());
out.close();
// get a runtime object
Runtime rt = Runtime.getRuntime();
// execute pgp from the command line
// e=encrypt a=ascii t=text file w=wipe the file
Process process = rt.exec(directory + “pgp -eatw ” + directory + filename + ” ” + pgpkey);
// wait for the execution to end
process.waitFor();
// read the armored ASCII file
File inputfile = new File(directory + filename + “.asc”);
BufferedReader isr = new BufferedReader(new FileReader(inputfile));
StringBuffer decrypted = new StringBuffer();
String line = “”;
while ((line = isr.readLine()) != null) {
decrypted.append(line + “\n”);
}
// close the reader
isr.close();
inputfile.delete();
// print out the encrypted string for kicks
System.out.println(decrypted.toString());
A quick summary. The PGP executable assumes that you’re encrypting and decrypting files, so I first take the string that I want to encrypt and write it to a text file using the File and FileWriter classes. Then I use the Runtime class to execute PGP from the command line, which encrypts the file and deletes the original plain text unencrypted file that I just created. I call the waitFor() method on the Process to make sure that the execution is complete, and then I read in resulting armored ASCII file using the File, FileReader and BufferedReader classes. Finally, I delete the armored ASCII file. Obviously in production you’d want to use a unique name for the file so that you don’t overwrite or delete a file that another thread just created. Other than that, are there any issues that I missed?
4 Comments