Decrypt byte array using AES algorithm - Java Security

Java examples for Security:AES

Description

Decrypt 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[] encryptedData = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(decrypt(encryptedData)));
    }/*from  w w  w  .java  2s  .  c  o m*/
    private static final String ALGO = "AES";
    private static final byte[] keyValue = "Ad0#2s!3oGyRq!5F".getBytes();
    /**
     * Decrypt byte array using AES algorithm
     * @param encryptedData
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);

        byte[] decValue = c.doFinal(encryptedData);
        return decValue;
    }
    private static Key generateKey() throws Exception {
        if (key == null)
            key = new SecretKeySpec(keyValue, ALGO);

        return key;
    }
}

Related Tutorials