środa, 25 maja 2011

Encryption/decryption of data in Java

Recently I came to the problem that the one of my colleagues utilities had to store some sensitive data (password) in it's configuration file (property file). Storing it it plain text would be a serious security flaw and therefore we had to find a way to store the password in an encrypted form using some key. Fortunately it is not that difficult in java - the apache common codec library becomes useful here. It provides much more functionality but what we used is the base64 encoding/decoding.

Below I enclose the example logic for encrypting the password:
    public byte[] encryptPassword(String pass, String key) throws Exception {
        DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secKey = keyFactory.generateSecret(keySpec);
        byte[] cleartext = pass.getBytes("UTF8");     

        Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
        cipher.init(Cipher.ENCRYPT_MODE, secKey);
        return Base64.encodeBase64(cipher.doFinal(cleartext));
    }


And to decrypt the password one can use the following method:
    public byte[] decryptPassword(String encryptedPass, String key) throws Exception {
        DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secKey = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decodeBase64(encryptedPass);

        Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
        cipher.init(Cipher.DECRYPT_MODE, secKey);
        return (cipher.doFinal(encrypedPwdBytes));
       
    }


I hope that these code snippets would be helpful also for you.

Brak komentarzy:

Prześlij komentarz