java - CipherOutputStream 无法写入 ByteArrayOutputStream

标签 java arrays

我正在尝试加密/解密文件,但 ByteArrayOutputStreamCipherOutputStream 出现问题。我能够加密文件,但无法解密文件。我尝试在 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/

相关文章:

php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?

javascript - 如何在 Javascript 中从小数组填充大数组

c++ - 使用多线程用值填充数组

arrays - 如何找到相同数量和颜色的组在 MATLAB 中给出不同的颜色?

java - 如何防止负数/负数

java初学者if/else if问题

java - 如何以编程方式添加 map fragment

java - 为 Box 类创建测试驱动程序并测试其所有方法

java - 如何从应用程序中准确找到 Java 应用程序使用了多少内存

c++ - 指针和结构数组