com.blackcrowsys.sinscrypto.AesEncryptor.java Source code

Java tutorial

Introduction

Here is the source code for com.blackcrowsys.sinscrypto.AesEncryptor.java

Source

/**
 * Black Crow Systems Limited.
 * 2014.
 * This code is released under GNU General Public License Version 3.
 * See LICENSE for full details of the license conditions.
 */
package com.blackcrowsys.sinscrypto;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

/**
 * @author ramindursingh
 *
 */
public class AesEncryptor implements Encryptor {

    private static final String AESMODE = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";

    /*
     * (non-Javadoc)
     *
     * @see com.blackcrowsys.sinscrypto.Encryptor#encrypt(java.lang.String,
     * java.lang.String)
     */
    @Override
    public String encrypt(String secretkey, String iv, String toEncrypt)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, InvalidAlgorithmParameterException, DecoderException {
        Cipher cipher = Cipher.getInstance(AESMODE);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretkey.getBytes(), AES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(Hex.decodeHex(iv.toCharArray())));
        return Base64.encodeBase64String(cipher.doFinal(toEncrypt.getBytes()));
    }

    /*
     * (non-Javadoc)
     *
     * @see com.blackcrowsys.sinscrypto.Encryptor#decrypt(java.lang.String,
     * java.lang.String)
     */
    @Override
    public String decrypt(String secretkey, String iv, String toDecrypt)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, InvalidAlgorithmParameterException, DecoderException {
        Cipher cipher = Cipher.getInstance(AESMODE);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretkey.getBytes(), AES);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(Hex.decodeHex(iv.toCharArray())));
        return new String(cipher.doFinal(Base64.decodeBase64(toDecrypt)));
    }
}