2
我想加密/解密文件,但我有一個ByteArrayOutputStream
和CipherOutputStream
問題。我能夠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){
}
}
我試圖關閉並沖洗CipherOutputStream後的outputstream。但對象仍然爲零。 – 2013-04-24 07:12:20
@XoXo:你能發佈你的更新代碼嗎?另外,請包含doCopy方法的代碼。 – Ankit 2013-04-24 08:20:05
以下是更新後的代碼 – 2013-04-24 08:33:08