[英]Speeding up encryption?
我有这个代码用于加密视频文件。
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
}
}
但我使用的文件非常大,使用这种方法需要花费太多时间。 我怎样才能加快速度呢?
这开始看起来很慢:
while((read = cis.read())!=-1)
{
fos.write(read);
fos.flush();
}
您正在一次读取和写入一个字节并刷新流 。 一次做一个缓冲区 :
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
另请注意,您只关闭fos
(不是cis
或fis
),您应该在finally
块中关闭所有这些。
你可以使用android NDK用C ++编写应用程序的那一部分,以获得显着的性能提升。 这看起来像是会从中受益的那种情况。 NDK可能已经有类似的东西。
你应该尝试Facebook Conceal。 它的速度非常快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.