com.giacomodrago.immediatecrypt.messagecipher.Compression.java Source code

Java tutorial

Introduction

Here is the source code for com.giacomodrago.immediatecrypt.messagecipher.Compression.java

Source

/*
 * ImmediateCrypt
 * Copyright (C) 2012 Giacomo Drago
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * http://giacomodrago.com/go/immediatecrypt
 * 
 */

package com.giacomodrago.immediatecrypt.messagecipher;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;

class Compression {

    public static byte[] compress(byte[] plaintext) {
        try {
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            GZIPOutputStream gzipStream = new GZIPOutputStream(writer);
            gzipStream.write(plaintext);
            gzipStream.flush();
            gzipStream.close();
            writer.close();
            return writer.toByteArray();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static byte[] decompress(byte[] plaintext) {
        try {
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            ByteArrayInputStream reader = new ByteArrayInputStream(plaintext);
            GZIPInputStream gzipStream = new GZIPInputStream(reader);
            IOUtils.copy(gzipStream, writer);
            gzipStream.close();
            writer.flush();
            writer.close();
            return writer.toByteArray();
        } catch (IOException ex) {
            return null; // Invalid source data
        }
    }

}