2013-04-24 137 views
2

我想加密/解密文件,但我有一个ByteArrayOutputStreamCipherOutputStream问题。我能够encrypt一个文件,但不能是decrypt该文件。我试图在CipherOutputStream之前关闭Stream。但是ByteArrayOutputStream对象保持为零,并且它不会在CipherOutputStream之后抑制任何字节。有任何想法吗?非常感谢。CipherOutputStream无法写入ByteArrayOutputStream

public static void encryptOrDecrypt(int mode, OutputStream os, InputStream is, String key) throws Throwable { 

    IvParameterSpec l_ivps; 
    l_ivps = new IvParameterSpec(IV, 0, IV.length); 

    DESKeySpec dks = new DESKeySpec(key.getBytes()); 
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); 
    SecretKey desKey = skf.generateSecret(dks); 
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 

    if (mode == Cipher.ENCRYPT_MODE) { 
     cipher.init(Cipher.ENCRYPT_MODE, desKey,l_ivps);  
     CipherInputStream cis = new CipherInputStream(is, cipher); 
     doCopy(cis, os); 
    } else if (mode == Cipher.DECRYPT_MODE) { 
     cipher.init(Cipher.DECRYPT_MODE, desKey,l_ivps);    
     CipherInputStream cis = new CipherInputStream(is, cipher);     
     doCopy(cis, os); 
     System.out.println("Decrypted"); 
    } 
} 

public static void doCopy(InputStream is, OutputStream os) throws IOException { 
    byte[] bytes = new byte[64]; 
    int numBytes; 
    System.out.println("doCopy Step1"); 
    System.out.println("is: "+is.read(bytes)); 
    while ((numBytes = is.read(bytes)) != -1) { 
     os.write(bytes, 0, numBytes); 
     System.out.println("doCopy Step2"); 
    } 
    os.flush(); 
    os.close(); 
    is.close(); 
} 

public static void writeFile(InputStream in){ 
    try { 
     String strContent;   
     BufferedReader bReader = new BufferedReader(new InputStreamReader(in)); 
     StringBuffer sbfFileContents = new StringBuffer(); 
     String line = null; 

     while((line = bReader.readLine()) != null){ 
      sbfFileContents.append(line); 
     } 
     System.out.println("File:"+sbfFileContents);    
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException ioe){ 

    } 
} 

回答

4
os.close(); 

CipherOutputStream cos = new CipherOutputStream(os, cipher); 

您冲洗和关闭的OutputStream,然后用它在CiptherOutputStream

创建CiptherOutputStream之前。

+0

我试图关闭并冲洗CipherOutputStream后的outputstream。但对象仍然为零。 – 2013-04-24 07:12:20

+0

@XoXo:你能发布你的更新代码吗?另外,请包含doCopy方法的代码。 – Ankit 2013-04-24 08:20:05

+0

以下是更新后的代码 – 2013-04-24 08:33:08