如何在内存中压缩并加密ZIP

  项目中遇到了一个问题,考虑到安全原因,需要将文件以二进制数据的方式打包成压缩文件,并且这个压缩文件是有密码的。

去Google上找了些API,下载来看了下,琢磨出了以下方法

  首先放API:

<!-- https://mvnrepository.com/artifact/de.idyl/winzipaes -->
        <dependency>
            <groupId>de.idyl</groupId>
            <artifactId>winzipaes</artifactId>
            <version>1.0.1</version>
        </dependency>

用了API后代码很简单,将一个二进制输入流塞进去,再输出成二进制流即可

    public static byte[] compressBytes(byte[] bytes, String entryName,
        String passWord) {
        ByteArrayOutputStream bout = null;
        ByteArrayInputStream bin = null;
        try {
            //二进制数组输出流
            bout = new ByteArrayOutputStream();
            bin = new ByteArrayInputStream(bytes.clone());
            AesZipFileEncrypter encrypter;
            encrypter = new AesZipFileEncrypter(bout, new AESEncrypterBC());
            encrypter.add(entryName, bin, passWord);
            encrypter.close();
            return bout.toByteArray();
        } catch (Exception e) {
            LOGGER.error("", e);
        } finally {
            StreamUtils.closeQuietly(bout, bin);
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        byte[] bytes = StreamUtils.read(new File("c:\\2.png"));
        StreamUtils.write(
            compressBytesInMemory(bytes, "2.png", "123456"),
            new FileOutputStream(new File("c:\\2.zip")));
    }

 

posted @ 2016-07-19 17:19  指尖挥舞  阅读(1261)  评论(0编辑  收藏  举报