码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-19 18:35:12      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

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

去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")));
    }

 

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

标签:

原文地址:http://www.cnblogs.com/naiyou/p/5685587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!