Flo354
Flo354

Reputation: 179

Increase speed of encryption AES android

I develop an android application for encrypt files on the phone. By searching, i found this topic : How to encrypt file from SD card using AES in Android?

The method works fine but it is very slow to encrypt files... At this line : byte[] d = new byte[8]; why only 8 bytes ? can't we set an higher value ?

Also, do you know a way to encrypt files fastly ? I heard of crypto++ for native code implementation but how can I implement JNI on my application ?

Thank you,

EDIT : Encryption function

public void encrypt (String RSAPrivateKey, String Key, byte[] iv, String zipname, ZipEncryptAsyncTask task) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException
    {
        FileInputStream     fis     = new FileInputStream   (zipname + ".temp");
        FileOutputStream    fos     = new FileOutputStream  (zipname);
        SecretKeySpec       sks     = new SecretKeySpec     (Base64.decode(Key, Base64.DEFAULT), "AES");
        IvParameterSpec     ivspec  = new IvParameterSpec   (iv);
        Cipher              cipher  = Cipher.getInstance    ("AES/CBC/PKCS5Padding");

        fos.write(String.valueOf(RSAPrivateKey.getBytes().length).getBytes());
        fos.write(RSAPrivateKey.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, sks, ivspec);
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        long size = 0;
        byte[] d = new byte[8];
        for(int b; (b = fis.read(d)) != -1; )
        {
            cos.write(d, 0, b);
            task.doProgress((size += 8));
        }

        cos.flush();
        cos.close();
        fis.close();

        new File(zipname + ".temp").delete();
    }

Upvotes: 2

Views: 1107

Answers (2)

rossum
rossum

Reputation: 15685

As an alternative, you could consider changing the cypher mode you are using. CBC mode must be used serially, block by block. Counter mode (CTR) can be run in parallel with different blocks being encrypted simultaneously. Of course there are overheads to parallel processing, and you will need to rework your code, but if buffer resizing does not give you enough speed gains, then it might be the next option to try.

Upvotes: 1

Flo354
Flo354

Reputation: 179

as @CodesInChaos said, a way to do this, is to increase the size of the buffer. Now I do a benchmark which determines the best size for the buffer and I use the optimal value.

Upvotes: 0

Related Questions