Java CipherOutputStream无法写入ByteArrayOutputStream
我正在尝试对文件进行加密/解密,但我在使用Java CipherOutputStream无法写入ByteArrayOutputStream,java,arrays,Java,Arrays,我正在尝试对文件进行加密/解密,但我在使用ByteArrayOutputStream和CipherOutputStream时遇到问题。我可以加密文件,但不能解密文件。我已尝试在CipherOutputStream之前关闭流。但是ByteArrayOutputStream对象保持为零,并且在CipherOutputStream之后不包含任何字节。有什么想法吗?非常感谢 public static void encryptOrDecrypt(int mode, OutputStream os, In
ByteArrayOutputStream
和CipherOutputStream
时遇到问题。我可以加密
文件,但不能解密
文件。我已尝试在CipherOutputStream之前关闭流。但是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){
}
}
您正在刷新并关闭outputstream,然后在CiptherOutputStream
在此之前创建CiptherOutputStream
您正在刷新并关闭outputstream,然后在CiptherOutputStream
在此之前创建
CiptherOutputStream
。我尝试在CipherOutputStream之后关闭并刷新outputstream。但是对象仍然为零。@XoXo:您能发布更新的代码吗?另外,还包括doCopy方法的代码。@XoXo:它在哪里?编辑您的问题并在其中添加更新的问题。@XoXo:有两个地方您已经创建了CipherInputStream,一个地方您已经纠正了我提到的问题,另一个地方您仍然在调用doCopy(cis,os);在os.flush和os.close被调用之后。甚至我在docopy中删除了flush和close。对象仍然为零。有两个CipherInputStream,一个用于加密,另一个用于解密。我尝试在CipherOutputStream之后关闭并刷新outputstream。但是对象仍然为零。@XoXo:您能发布更新的代码吗?另外,还包括doCopy方法的代码。@XoXo:它在哪里?编辑您的问题并在其中添加更新的问题。@XoXo:有两个地方您已经创建了CipherInputStream,一个地方您已经纠正了我提到的问题,另一个地方您仍然在调用doCopy(cis,os);在os.flush和os.close被调用之后。甚至我在docopy中删除了flush和close。对象仍然为零。有两个CipherInputStream,因为一个用于加密,另一个用于解密。
os.close();
CipherOutputStream cos = new CipherOutputStream(os, cipher);