Google Keyczar is a new Google toolkit for data encryption. We saw in a
previous post how to create the private and public key files for RSA encryption.
Let's now see how to use them by integrating the Keyczar library in a Java project.
It's actually extremely simple.
First, let's see the code from Bob's perspective. Bob encrypts the data using a public key which Alice has given him (and maybe other people). To do this we will use a class called BobsApp which will specifically handle encryption using the public key folder (you'll want to check its location: it should be rsakeys\publickeys\ and the rsakeys folder should be located at the same level as the BobsApp class file).
package keyczartest;
import org.keyczar.Encrypter;
import org.keyczar.exceptions.KeyczarException;
public class BobsApp
{
private Encrypter encrypter; // used to crypt
public BobsApp() throws KeyczarException
{
String publickey=this.getClass().getResource("rsakeys/publickeys").
getFile();
this.encrypter=new Encrypter(publickey);
}
public String process(String data) throws KeyczarException
{
if (data==null) return null;
return this.encrypter.encrypt(data);
}
}
Now, let's do the same thing from Alice's perspective. She will receive Bob's (and maybe other people's) encrypted messages, but she alone can decrypt them using her private key. (You'll want to check the private key folder location: it should be rsakeys and the rsakeys folder should be located at the same level as the BobsApp and AlicesApp class files).
This is the Java utility class which specifically handles decryption:
package keyczartest;
import org.keyczar.Crypter;
import org.keyczar.exceptions.KeyczarException;
public class AlicesApp
{
private Crypter crypter; // used to decrypt
public AlicesApp() throws KeyczarException
{
String privatekey=this.getClass().getResource("rsakeys").
getFile();
this.crypter=new Crypter(privatekey);
}
public String process(String data) throws KeyczarException
{
if (data==null) return null;
return this.crypter.decrypt(data);
}
}
Now, let's create our main method which we can use to run the project:
import keyczartest.AlicesApp;
import keyczartest.BobsApp;
public class Keyczarette
{
public static void main(String[] args)
{
try
{
String secretText="For Alice's eyes only. Signed: Bob";
String bobsMessage=new BobsApp().process(secretText);
System.out.println("Bob sends: " + bobsMessage);
AlicesApp app=new AlicesApp();
String alicesMessage=new AlicesApp().process(bobsMessage);
System.out.println("What Alice reads: " + alicesMessage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Just one last note, if you get a message like "incorrect class version, 50 should be 49" or something along those lines, it means you are not running the correct version of java (i.e. the KeyCzar classes were compiled with a later version).
Straight to the point! =D
Could it get any simpler than that?