Decrypts the given message using the given key with AES-CBC. - Java Security

Java examples for Security:AES

Description

Decrypts the given message using the given key with AES-CBC.

Demo Code


//package com.java2s;

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Main {
    public static final int AES_PARAM_LEN = 18;

    /**/*  ww  w.  j  a va 2s.co m*/
     * Decrypts the given message using the given key with AES-CBC.
     *
     * @param decrypt  the message (in bytes)
     * @param keySpec  the secret key
     * @return decrypted message
     */
    public static byte[] decrypt(byte[] decrypt, SecretKeySpec keySpec) {
        byte[] message = null;

        try {
            // Extract the cipher parameters from the end of the input array
            byte[] cipherText = new byte[decrypt.length - AES_PARAM_LEN];
            byte[] paramsEnc = new byte[AES_PARAM_LEN];

            System.arraycopy(decrypt, 0, cipherText, 0, cipherText.length);
            System.arraycopy(decrypt, cipherText.length, paramsEnc, 0,
                    paramsEnc.length);

            // Initialize the parameters
            AlgorithmParameters params = AlgorithmParameters
                    .getInstance("AES");
            params.init(paramsEnc);

            // Initialize the cipher for decryption
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, params);

            // Decrypt the ciphertext
            message = cipher.doFinal(cipherText);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return message;
    }
}

Related Tutorials