Decompress byte array using Deflater/Inflater method - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Decompress byte array using Deflater/Inflater method

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(decompress(data)));
    }/*from w  w  w .jav  a 2s.  co m*/
    private static final String ALGO = "AES";
    private static final byte[] keyValue = "Ad0#2s!3oGyRq!5F".getBytes();
    /**
     * Decompress byte array using Deflater/Inflater method
     * @param data
     * @return
     * @throws IOException
     * @throws DataFormatException
     * @throws Exception
     */
    public static byte[] decompress(byte[] data) throws IOException,
            DataFormatException, Exception {

        data = decrypt(data);
        Inflater inflater = new Inflater();

        inflater.setInput(data);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                data.length);
        byte[] buffer = new byte[1024];
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        outputStream.close();
        byte[] output = outputStream.toByteArray();

        return output;
    }
    /**
     * 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