0

我正在尝试使用 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.file.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 BufferedInputStream(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");
        aesCipher.init(encryptMode, secretkey);
        FileOutputStream out = new FileOutputStream("temp.zip");
        BufferedOutputStream outputStream = new BufferedOutputStream(out);
        aesCipher.init(encryptMode, secretkey);
        CipherOutputStream cipherStream = new CipherOutputStream(outputStream, aesCipher);

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



4

0 回答 0