AES encrypt byte array and return byte array - Java Security

Java examples for Security:AES

Description

AES encrypt byte array and return byte array

Demo Code


//package com.java2s;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {


    /**// w ww .  jav  a2 s. com
     * @param iv
     * @param key
     * @param text
     * @return
     */
    public static byte[] encrypt(byte[] iv, byte[] key, byte[] text) {

        try {

            AlgorithmParameterSpec algorithmParameterSpec = new IvParameterSpec(
                    iv);

            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,
                    algorithmParameterSpec);

            return cipher.doFinal(text);

        } catch (Exception exception) {

            return null;

        }

    }
}

Related Tutorials