Tuesday, 20 November 2012

Encryption And Decryption in Java



import javax.crypto.*;
import javax.crypto.spec.*;
import org.apache.commons.codec.binary.*;

 public class DESDecrypt {
 
    private String characterEncoding = "UTF-8";
    private String cipherTransformation = "AES/CBC/PKCS5Padding";
    private String aesEncryptionAlgorithm = "AES";  
 
    private byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector) throws Exception
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
        cipherText = cipher.doFinal(cipherText);
        return cipherText;
    }

    private byte[] encrypt(byte[] plainText, byte[] key, byte[] initialVector) throws Exception
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        plainText = cipher.doFinal(plainText);
        return plainText;
    }

    private byte[] getKeyBytes(String key) throws Exception{
 
        byte[] keyBytes= new byte[16];
        byte[] parameterKeyBytes= key.getBytes(characterEncoding);
        System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));      
        return keyBytes;
    }
 
    public String encrypt(String plainText, String key) throws Exception{
 
        byte[] plainTextbytes = plainText.getBytes(characterEncoding);
        byte[] keyBytes = getKeyBytes(key);
        return Base64.encodeBase64String(encrypt(plainTextbytes, keyBytes, keyBytes));
    }

    public String decrypt(String encryptedText, String key) throws Exception{
     
        byte[] cipheredBytes = Base64.decodeBase64(encryptedText);
        byte[] keyBytes = getKeyBytes(key);
     
        return new String(decrypt(cipheredBytes, keyBytes, keyBytes), characterEncoding);
    }
 
}

No comments:

Post a Comment