Java大文件AES加密非常慢

问题描述

我正在尝试使用AES / CBC算法加密512 Mb文件。这大约需要7秒的时间。如何减少加密时间并使之更快。

我正在使用固定密钥,并尝试使用CipherOutStream以及cipher.update()而不是cipher.dofinal()。不过,它仍然需要大约7秒钟。

使用以下加密方法来加密512 MB文件通常需要花费多少时间。在配备16 GB内存和2 GHz四核Intel Core i5处理器的Mac上,我花了6秒钟。我正在使用JDK 11执行。这是正常现象还是我的代码响应缓慢。我应该担心吗?如何缩短加密时间。

package com.encrypterdecrypter;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@SpringBootApplication
public class DemoApplication {
    private static final String SECRET_KEY = "aesencryptionKey";
    private static final String initVector = "encryptionIntVec";

    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoApplication.class,args);
        File inputFile = new ClassPathResource("fivetwelvemb.zip").getFile();
        InputStream inputStream = new FileInputStream(inputFile);
        SecretKeySpec secretkey = new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"),"AES");


        long startTime = System.currentTimeMillis();
        OutputStream encryptStream = encryptDecryptBinary(inputStream,Cipher.ENCRYPT_MODE,secretkey);
        long endTime = System.currentTimeMillis();
        System.out.println("Encryption Time in ms : " + (endTime - startTime));

    }

    public static OutputStream encryptDecryptBinary(InputStream inputStream,int encryptMode,SecretKeySpec secretkey) throws Exception {
        Cipher aesCipher = Cipher.getInstance("AES/CBC/nopadding");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        aesCipher.init(encryptMode,secretkey);
        OutputStream out =  new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(out,aesCipher);

       /* byte[] encryptedData = aesCipher.doFinal(inputStream.readAllBytes()); */

        byte[] buf = new byte[8192];
        int numRead = 0;
        while ((numRead = inputStream.read(buf)) >= 0) {
            cipherOutputStream.write(buf,numRead);
        }
        cipherOutputStream.close();
        return out;
    }
}
```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)