Reputation: 13
I am trying to encrypt a huge .txt file, The problem is the decryption is very slow, I tried AES,DES,3DES,BlowFish algorithms with different modes but the decryption still slow
here is my code :
static
{
try
{
//ciphers initialization
SecretKey secretKey = THE_KEY;
//Decryption cipher
Cipher dec = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] ivDec = new byte[dec.getBlockSize()];
IvParameterSpec ivparDec = new IvParameterSpec(ivDec);
dec.init(Cipher.DECRYPT_MODE, secretKey,ivparDec);
//Encryption cipher
Cipher enc = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[enc.getBlockSize()];
IvParameterSpec ivpar = new IvParameterSpec(iv);
enc.init(Cipher.ENCRYPT_MODE, secretKey,ivpar);
}
catch (Exception e){e.printStackTrace();}
}
Here is the encrypt/decrypt methods :
public static String encrypt (String data)
{
String encData = null;
byte [] arr = null;
try
{
arr = enc.doFinal(data.getBytes("UTF-8"));
//convert to base 64
String base64 = Base64.encodeBase64String(arr);
encData = base64;
}
catch(Exception e){e.printStackTrace();}
return encData;
}
public static String decrypt (String data)
{
String decData = null;
byte [] arr = null;
try
{
//convert base64 to bytes[]
byte[] base64 = Base64.decodeBase64(data);
arr = dec.doFinal(base64);
decData = new String(arr,Charset.forName("UTF-8"));
}
catch(Exception e){e.printStackTrace();}
return decData;
}
How can I improve the performance of this code ?
Upvotes: 0
Views: 2700
Reputation: 93978
First of all you should try and stream your data or - even better - map your files using java.nio
use Cipher.update
. Then you can directly encrypt/decrypt the binary data. Reading everything in memory may result in disk trashing if the data doesn't fit in the available RAM, and even out-of-memory errors.
Converting your plaintext to String
will make things worse, especially since Oracle's Java (before 9) uses 16 bit characters for ASCII internally. Encoding it as base 64 is unneeded if you're going to store it as binary file in the first place. Base 64 adds even more to the memory overhead.
Your runtime makes a lot of difference. The latest Oracle provided runtimes have a lot of performance improvements, so make sure you run the latest server VM so you can use things like AES-NI intrinsics.
Upvotes: 2