2012-02-29 41 views
3

我有這個代碼來加密視頻文件。加速加密?

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 
    } 
} 

但我使用的文件非常大,使用這種方法需要很多時間。 我該如何加快速度?

+0

Encyrption是資源密集型的。整個想法是,你正在以一種複雜的方式破壞內容。 – mcfinnigan 2012-02-29 11:08:54

+0

你得到什麼樣的速度?你有沒有嘗試*映射*文件,並在ByteBuffer的返回(ps不知道,如果這可能爲android,忽略標籤)執行加密? – 2012-03-01 00:45:26

+0

我是新手我不知道它的可能 – Navdroid 2012-03-01 05:19:46

回答

5

嗯,這看起來開始很慢:

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(不cisfis),並且你應該關閉所有的人都在finally塊。

+0

我的文件大約是300MB,這個方法使得它比以前更慢 – Navdroid 2012-02-29 11:20:52

+2

@Navdroid:這比讀取和寫入單個字節的速度慢*我覺得很難相信。 – 2012-02-29 11:29:30

+0

我是新來的這個先生..我也發現這個令人困惑但是舊的方法比你的方法更快... – Navdroid 2012-02-29 11:32:13

2

您可以使用android NDK使用C++編寫應用程序的這一部分,以獲得顯着的性能提升。這看起來像會從中受益的那種情況。而且NDK可能已經有了類似的東西。