Alex Amiryan
Alex Amiryan

Reputation: 1382

AES256 Encryption/Decryption speed

I am writing an application which encrypts and decrypts files. I am using CipherInputStream and CipherOutputStream for enryption/decryption process using AES256 bit cipher.

My problem is if I take byte array and write to file makeing encryption on the fly it takes about 2 times less time than if I decrypt file creating a byte array. It is strange because as I know AES encryption and decryption are symmetric processes and they should take same amount of time to complete.

Any ideas?

Upvotes: 1

Views: 3271

Answers (2)

Chao Chen
Chao Chen

Reputation: 21

Not sure what your code looks like.

I fixed a similar slow decryption problem. My original code referenced the most popular Android encryption/decryption examples. It use a CipherOutputStream to encrypt and CipherInputStream to decrypt. I found the decryption is about 4 times slower that encryption. Eventually I found the problem is the CipherInputStream. It's much slower than CipherOutputStream. The fix is to use CipherOutputStream for both encryption and decryption, and flip the Cipher from encryp to decrypt. After that, decryption is as fast as encryption.

Their could be other ways to achieve that if you don't want to output the decrypted to a file. Maybe don't use cipher stream at all. Just decrypt buffers. I didn't try that yet.

Upvotes: 2

Robert
Robert

Reputation: 42650

There are a lot of postings here on Stackoverflow complaining about slow I/O operations on Android. Very often the problem is a bad block-size for performing th write operations.

Flash memory as used in Smartphones is organized in large blocks of several kilobytes - therefore for optimal write speed you should only write blocks of 4KB or multiple of it.

Ciphers like AES work block-wise on blocks of 8 bytes - this may lead to massive performance drain.

I would recommend to send the output of the CipherOutputStream through a BufferedOutputStream with a buffer size of 4 or 16 KB. This should significantly speed-up the process.

Additionally you have to consider that writing to flash memory is always slower than reading.

Upvotes: 5

Related Questions