Ariyan
Ariyan

Reputation: 15158

Optimizing File Encryption in Java

I'm developing an application that encrypts its input files.
My Code is this for encrypting files (File size differs from some KB to 4GB):

    SecretKeySpec   key = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    Cipher          cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    byte[] block = new byte[8];
    int i;

    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    BufferedInputStream bIn=new BufferedInputStream(new ProgressMonitorInputStream(null,"Encrypting ...",new FileInputStream("input")));
    CipherInputStream       cIn = new CipherInputStream(bIn, cipher);
    BufferedOutputStream bOut=new BufferedOutputStream(new FileOutputStream("output.enc"));

    int ch;
    while ((i = cIn.read(block)) != -1) {
        bOut.write(block, 0, i);
    }
    cIn.close();
    bOut.close();

Can I make it more optimum (Time,IO,CPU)?
How?

Thanks

Upvotes: 0

Views: 340

Answers (3)

FdL
FdL

Reputation: 11

What you can do is to you use AESFastEngine from bouncycastle library to accelerate aes block computation.

crypto/src/org/bouncycastle/crypto/engines

This fast engine uses T tables which are rounded precomputed table and for sure will have a gain in performance.

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

Picking a better byte[] block size will help (something in the 8k to 1MB range, test to find the optimium size for your scenario), but other than that there's not much you can do to make it faster (assuming you maintain the current encryption algorithm).

Upvotes: 1

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

This is a complicated and difficult question to answer. First of all, encrypting 4GB worth of file is going to take time no matter what you do.

A lightweight encryption algorithm like the Hummingbird will help you get there - but, you have to make sure that wherever you're using this, AES isn't absolutely necessary.

Upvotes: 2

Related Questions