如何在内存中压缩并加密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")));
    }

 

转载于:https://www.cnblogs.com/naiyou/p/5685587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值