2

我正在尝试加密/解密文件,但我遇到了ByteArrayOutputStreamand的问题CipherOutputStream。我可以encrypt存档,但不能成为decrypt文件。我尝试在 CipherOutputStream 之前关闭 Stream。但是 ByteArrayOutputStream 对象保持为零,并且在 CipherOutputStream 之后不包含任何字节。有任何想法吗?非常感谢。

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

1 回答 1

4
os.close();

CipherOutputStream cos = new CipherOutputStream(os, cipher);

您正在刷新和关闭输出流,然后在其中使用它CiptherOutputStream

在此之前创建CiptherOutputStream

于 2013-04-24T06:55:47.723 回答