AES encrypt byte array by byte array key - Java Security

Java examples for Security:AES

Description

AES encrypt byte array by byte array key

Demo Code


//package com.java2s;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] input = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        byte[] key = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(encrypt(input, key)));
    }/* ww w  . ja v a  2s  .  com*/

    public static byte[] encrypt(byte[] input, byte[] key)
            throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException {
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(input);
    }
}

Related Tutorials