我有一个读取文件(例如* .zip)的问题,并使用3DES对其进行加密,使用加密文件的名称生成的secretKey。 然后我需要解密这个文件,然后把它写在硬盘上。 我试图解决这个问题,但解密文件时卡住了。3des加密/解密文件java
这里是加密
public class Encryptor {
private static String inputFilePath = "D:/1.txt";
public static void main(String[] args) {
FileOutputStream fos = null;
File file = new File(inputFilePath);
String keyString = "140405PX_0.$88";
String algorithm = "DESede";
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] fileByteArray = new byte[fileInputStream.available()];
fileInputStream.read(fileByteArray);
for (byte b : fileByteArray) {
System.out.println(b);
}
SecretKey secretKey = getKey(keyString);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
ObjectOutputStream objectOutputStream = new ObjectOutputStream
(new CipherOutputStream
(new FileOutputStream
("D:/Secret.file"), cipher));
objectOutputStream.writeObject(fileByteArray);
objectOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static SecretKey getKey(String message) throws Exception {
String messageToUpperCase = message.toUpperCase();
byte[] digestOfPassword = messageToUpperCase.getBytes();
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
return key;
}
}
的代码这里是解密
public class Decryptor {
public static void main(String[] args) {
try {
File inputFileNAme = new File("d:/Secret.file");
FileInputStream fileInputStream = new FileInputStream(inputFileNAme);
FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
SecretKey secretKey = getKey(keyString);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
ObjectInputStream objectInputStream = new ObjectInputStream
(new CipherInputStream(fileInputStream, cipher));
System.out.println(objectInputStream.available());
while (objectInputStream.available() != 0) {
fileOutputStream.write((Integer) objectInputStream.readObject());
System.out.println(objectInputStream.readObject());
}
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
objectInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static SecretKey getKey(String message) throws Exception {
String messageToUpperCase = message.toUpperCase();
byte[] digestOfPassword = messageToUpperCase.getBytes();
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
return key;
}
}
当我尝试解密我的文件,我没有得到在输出文件中的任何代码。
我试过做调试,并看到,objectInputStream.available()
总是包含0.
请告诉我,我该如何解决这个问题,以及为什么会发生。
'close()'之前的'flush()'是多余的,就像关闭包装在其他流中的流一样。这些都没有解决发送方面的问题。 – EJP 2014-12-08 08:59:56
这个解决方案不是一个不错的和干净的解决方案,它是一个解决OP问题的_quickfix_。如果需要的话,它可以被很好地和干净地重写。 (事实上,我为你的答案+1了@EJP) – superbob 2014-12-08 10:00:08