Long time member of the Java community. Author of JHTML and the SmugMug Java API, worked with the DZone crew for a while and Product Services Manager at Genuitec. Also the creator of The "Break it Down" Blog and comedy site Up My Own Ass. Riyad has posted 6 posts at DZone. View Full User Profile

Easy Encryption in Java and Python with Keyczar

08.20.2008
| 9400 views |
  • submit to reddit
Do you need to encrypt small text data, like serial numbers or customer numbers in your web application?  With the amount of data being transmitted online and the increasing need to protect customers against identity theft, encryption is the one and only choice to keep customers safe. Unfortunately, implementing encryption is a daunting task and the circumstance often leads to security holes. Like most developers, we aim to protect our customers, and keeping on top of the latest encryption techniques is easily a full time job.

If you have been thinking about adding encryption to your application there is a great tool that will make your life a lot easier: Keyczar.

Keyczar is another great opensource tool to come out of Google recently, and it aims to deliver all the benefits of encryption without the headache. Keyczar aims to do a majority of the grunt work and let you, the application developer, do what you do best: develop. Some of the features of the toolkit (straight from the website) are:

  • A simple API
  • Key rotation and versioning
  • Safe default algorithms, modes, and key lengths
  • Automated generation of initialization vectors and ciphertext signatures
  • Java and Python implementations (C++ coming soon)
  • International support in Java (Python coming soon)

The Java code example on the website is fairly simple, and only requires 2 lines of code:

	Crypter crypter = new Crypter("/path/to/your/keys");
String ciphertext = crypter.encrypt("Secret message");

You can grab the Java 6 compatible library from here, or the Java 5 compatible library from here, and can begin digging through the Javadocs if you like here. If you get a chance to try the library out, let us know what you think.

To get to the point where you can start including the above lines in your java app, you’ll need to do a couple of setup steps. For this example, we’ll be creating a setup that encrypt strings based on a symmetric cipher. This means that there is a key to encrypt and decrypt a particular message.

First, download the version of keyczar05b that fits your current java installation (1.5 or 1.6) from the Keyczar website here. You’ll also need to grab GSON and LOG4J to meet the requirements listed on the Java Dependencies page.

When you unzip the GSON and LOG4J packages, locate their respective jar and place them both in the same directory as the keyczar05b-1.x.jar. From this point on, this example assumes $(dir) is the location of all the required files.

Open up a terminal, go to your $dir directory and setup the classpath (NOTE: Line breaks are put in place for readability, please type the following command all on a single line):

export CLASSPATH="$(dir)/keyczar05b-1.5.jar:
$(dir)/gson-1.1.1.jar:
$(dir)/log4j-1.2.15.jar

Then create a directory to store your keys, and make the key set:

mkdir $(dir)/keys
java -cp $CLASSPATH org.keyczar.KeyczarTool create
--location=$(dir)/keys/
--purpose=crypt
--name=Keyset

Then you need to make a primary key:

java -cp $CLASSPATH org.keyczar.KeyczarTool addkey
--location=$(dir)/keys/ --status=primary

At this point you now have a symmetric key to use to encrypt small text blobs (like customer ids!!). Here is a sample java class that will encrypt “Hello World”, based on the key I just set up, and print it out:

import java.lang.*;
import org.keyczar.*;
 
public class SampleEncrypter {
public static void main(String args[])
{
 
//grab command line arguments, and spit out error if not used right
if ( args.length != 1 ) {
System.err.println ("usage: java SampleEncrypter [keydirectory]");
return;
}
Crypter crypter;
try{
crypter = new Crypter(args[0]);
String ciphertext = crypter.encrypt("Hello World");
System.out.println("Cyphered Phrase: \n"+ciphertext+"\n");
}
catch(Exception e){
System.out.println("Something bad happened");
System.out.println(e.toString());
}
}

Output:

bash-3.2$ javac -cp $CLASSPATH sampleencrypter.java
bash-3.2$ java -cp $CLASSPATH:$(dir) sampleencrypter keys
Cyphered Phrase:
AV_GuyDgAXgGKS6oeFH5MiaARyG3fXY4_RSRinpSrzITj9wXQdhdX7ozMM9RiXNYfdpAkD_xLKtv

There is more information about setting up different key types in the PDF they have listed on the website, but this should at least get you going using a symmetric key!

Published at DZone with permission of its author, Riyad Kalla.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)