Encrypt byte array using AES algorithm - Java Security

Java examples for Security:AES

Description

Encrypt byte array using AES algorithm

Demo Code


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Key;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] Data = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(encrypt(Data)));
    }//w ww. j  av a  2  s  .  c  o  m
    private static final String ALGO = "AES";
    private static final byte[] keyValue = "Ad0#2s!3oGyRq!5F".getBytes();
    /**
     * Encrypt byte array using AES algorithm
     * @param Data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data);
        //String encryptedValue = new BASE64Encoder().encode(encVal);
        return encVal;
    }
    private static Key generateKey() throws Exception {
        if (key == null)
            key = new SecretKeySpec(keyValue, ALGO);

        return key;
    }
}

Related Tutorials