Java large file AES Encryption is very slow

91 Views Asked by At

I'm trying to encrypt a 512 Mb file with AES/CBC algorithm. It is taking around 7 sec which is too much. How to reduce the encryption time and make it faster.

I'm using a fixed key and tried using CipherOutStream as well as cipher.update() instead of cipher.dofinal(). Still, it is taking around 7 secs.

How much time generally it would take to encrypt a 512 MB file with the below encryption. It is taking 6 seconds for me on a Mac with 16 GB memory and 2 GHz Quad-Core Intel Core i5 processor. I'm using JDK 11 for execution. Is it normal or my code is responding slow. Should I be concerned? How to improve the time for encryption.

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;
    }
}



0

There are 0 best solutions below