我正在尝试开发一个系统,该系统将解密文件,然后允许授权用户查看它而不保存解密文件。这是为了确保其他用户无法打开解密文件。
以下代码生成了文件输出。
public NewJFrame() {try{
String key = "squirrel123";
FileInputStream fis2 = newFileInputStream("encrypted.mui");
FileOutputStream fos2 = new FileOutputStream("decrypt.rar");
decrypt(key, fis2, fos2);
Desktop dk=Desktop.getDesktop();
File f = new File("decrypt.rar");
dk.open(f);
}
catch (Throwable e) {
JOptionPane.showMessageDialog(null, e);
}}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
如何在不使用FileOutputStream的情况下解密文件,然后允许授权用户在解密后查看文件?
答案 0 :(得分:1)
如果您不想将其写入物理文件,而只是显示数据,则可以使用其他编写器,然后使用FileOutputStream。
例如,您可以创建一对PipedStream,解密然后读取结果。
String key = "squirrel123";
FileInputStream fis2 = newFileInputStream("encrypted.mui");
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
decrypt(key, fis2, pis);
BufferedReader reader = new BufferedReader(new InputStreamReader(pis));
String line;
while( (line=reader.readLine()) != null ){
System.out.println(line);
}