2011-05-04 77 views
0

無阻塞密碼流,即使仍然塊你好,我使用的密碼在這個崗位5777105應用使用帶有插座

但直到達到解密代碼仍然塊緩衝區的大小。你知道另一種方法來使它不被阻塞嗎?請注意,解密部分正在Android上運行。

加密部分:

CipherInputStream cis; 
    String salt = "123456789"; 
    String password = "abcdEFGH"; 

    password = password.concat(salt); 
    String validpassword = password.substring(0, 16); 
    SecretKeySpec secretKey = new SecretKeySpec(validpassword.getBytes(),"AES"); 
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(salt.getBytes()); 

    try { 
     // Creation of Cipher objects 
     Cipher encrypt = 
     Cipher.getInstance("AES/CFB8/NoPadding"); 
     encrypt.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec); 

     // Open the file 
     try { 
      fis = new FileInputStream(file); 
     } catch(IOException err) { 
      System.out.println("Cannot open file!"); 
      return null; 
     } 
     cis = new CipherInputStream(fis, encrypt); 

     // Write to the Encrypted file 
     fos = new FileOutputStream(desFile); 
     byte[] b = new byte[256]; 
     int i = cis.read(b); 
     while (i != -1) { 
      fos.write(b, 0, i); 
      i = cis.read(b); 
     } 

解密部:

CipherInputStream cis; 
    String salt = "123456789"; 
    String password = "abcdEFGH"; 

    password = password.concat(salt); 
    String validpassword = password.substring(0, 16);   
    SecretKeySpec secretKey =new SecretKeySpec(validpassword.getBytes(),"AES");   
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(salt.getBytes()); 

    try { 
     // Creation of Cipher objects 
     Cipher decrypt = 
       Cipher.getInstance("AES/CFB8/NoPadding"); 
     decrypt.init(Cipher.DECRYPT_MODE, secretKey,paramSpec); 

     // Open the Encrypted file 
     cis = new CipherInputStream(is, decrypt); 

     int bytesRead; 
     int current = 0; 
     byte[] b = new byte[256]; 
     bytesRead = cis.read(b,0,256); 

回答

0

原因cis.read被阻塞很簡單:周圍的流套接字的密碼流包裝(你通過套接字流密碼流構造函數),因此無論何時調用密碼流上的讀取操作,都將導致密碼流中的代碼從套接字讀取數據,以便它可以解密數據。這是從哪裏(從套接字流讀取)代碼塊。

你應該沒有任何問題阻止您在UI線程中運行此代碼的單元。您可以在另一個工作線程上運行此代碼,以便您的UI不會凍結