Thursday 11 August 2011

How to use Java Security API to crypt some data

Recently, I have been asked by a friend of mine a library he could use to crypt credentials (login, pwd and …), therefore I told him he could use Java security API. But the problem is that he was a new Java programmer, and this API seemed very complicated for him, he was wanting a library where he could find two methods with simple signatures (one to encrypt and another to decrypt). Therefore, I implemented a façade that will hide the specific aspects of this library.
I will then use this tutorial to explain how I have done to reach this objective.


Design
As you know, the algorithms used with the Java Security API use a key to crypt data, therefore the very first thing to do is to generate this key, and save it. You could then use this key, later, to encrypt and decrypt your data. To reach our objectives, we have then to provide a method to generate a key, in such manner that it will be very easy for a very beginner to save it (what‘s better than String J?). After we’ll provide a method to encrypt a string with a string key and return a String, and the last method with same signature will be used to decrypt encoded string.
Once we have these methods, how could we proceed to reach our objectives? It’s quite simple. We use a property file for example where we’ll store the key. When, we first generate the property file or when this file is corrupted, we generate the key and save it. Therefore, later when we have to encrypt or decrypt some data, we only read our key and use it. I know, you prefer to see code, no problem, let’s move
Implementation
In this implementation we use DES algorithm, but you could change it without efforts. And all this methods have been marked static, since they don’t belong to any context.
The “generateKey” method
As we have told before, we’ll use this method to generate the key we’ll use later to encode or decode our String.
    public static String generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        keyGen.init(56);
        Key key = keyGen.generateKey();
        return new String(key.getEncoded());
    }
We first indicate which algorithm we want to use (DES), therefore we generate the key. Since this key is an array of byte, we convert it to a String, before returning it.
The “getEncodedString” method
After having generated our key, we’ll use this method to encode our string
    public static String getEncodedString(String text, String key) throws
            Exception {
        SecretKeySpec keyS = new SecretKeySpec(key.getBytes(), “DES”);
        Cipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”);
        cipher.init(Cipher.ENCRYPT_MODE, keyS);
        byte[] cipherText = cipher.doFinal(text.getBytes());
        return new String(cipherText);
    }
As with the first method, we first start by indicate which algorithm we’ll use, we therefore initialize a cypher with our key converted to array of bytes. Notice that we initialize our cypher with the encrypt mode (Cipher.ENCRYPT_MODE). We then use the doFinal method of the cypher to encrypt String, and as with the previous method we convert result to String before returning it.
The “getDecodedString” method
This method works as the previous, the only difference is the initialization mode of the cypher.
    Public static String getDecodedString(String text, String key) throws
            Exception {
        SecretKeySpec keyS = new SecretKeySpec(key.getBytes(), “DES”);
        Cipher cipher = Cipher.getInstance(“DES/ECB/PKCS5Padding”);
        cipher.init(Cipher.DECRYPT_MODE, keyS);
        byte[] newPlainText = cipher.doFinal(text.getBytes());
        return new String(newPlainText);
    }
As with the first method, we first start by indicate which algorithm we’ll use, we therefore initialize a cypher with our key converted to array of bytes. Notice that we initialize our cypher with the decrypt mode (Cipher.DECRYPT_MODE). We then use the doFinal method of the cypher to decrypt String, and as with the previous method we convert result to String before returning it.
Conclusion
In this very short tutorial, we have presented a way to use Java Security API to encrypt and decrypt data in a simple way. This tutorial has just scratched the surface of this huge library, giving then the opportunity to less experienced Java developer to use a secure and simple way to protect their data. If you want any help to a specific aspect of this library or this tutorial, don’t hesitate to let a comment, I’ll then provide another tutorial dealing with your needs. I hope, this tutorial will be for any help.