I have this code for encrypting video files.
public static void encryptVideos(File fil,File outfile)
{
try{
FileInputStream fis = new FileInputStream(fil);
//File outfile = new File(fil2);
int read;
if(!outfile.exists())
outfile.createNewFile();
FileOutputStream fos = new FileOutputStream(outfile);
FileInputStream encfis = new FileInputStream(outfile);
Cipher encipher = Cipher.getInstance("AES");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
//byte key[] = {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
SecretKey skey = kgen.generateKey();
//Lgo
encipher.init(Cipher.ENCRYPT_MODE, skey);
CipherInputStream cis = new CipherInputStream(fis, encipher);
while((read = cis.read())!=-1)
{
fos.write(read);
fos.flush();
}
fos.close();
}catch (Exception e) {
// TODO: handle exception
}
}
but the files which I am using are very big and using this method it takes too much time. How can I speed this up?
Well this looks very slow to start with:
while((read = cis.read())!=-1)
{
fos.write(read);
fos.flush();
}
You're reading and writing a single byte at a time and flushing the stream. Do it a buffer at a time:
byte[] buffer = new byte[8192]; // Or whatever
int bytesRead;
while ((bytesRead = cis.read(buffer)) != -1)
{
fos.write(buffer, 0, bytesRead);
}
fos.flush(); // Not strictly necessary, but can avoid close() masking issues
Also note that you're only closing fos (not cis or fis), and you should be closing all of them in finally blocks.
You could use the android NDK to write that part of your app with C++ to get significant performance boost. This looks like the kind of situation that would benefit from it. And there might already be something like this made with NDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With