我正在尝试加密/解密文件,但是ByteArrayOutputStreamCipherOutputStream存在问题。我可以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){

    }
}

最佳答案

os.close();

CipherOutputStream cos = new CipherOutputStream(os, cipher);


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

在此之前创建CiptherOutputStream

关于java - CipherOutputStream无法写入ByteArrayOutputStream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16185245/

10-09 07:42