如何在没有文件输出的情况下用Java显示解密后的文件?
我正试图开发一个系统,将解密一个文件,然后允许授权用户查看它而不保存解密的文件。这是为了确保其他用户无法打开解密的文件 以下代码生成了一个文件输出如何在没有文件输出的情况下用Java显示解密后的文件?,java,encryption,netbeans,Java,Encryption,Netbeans,我正试图开发一个系统,将解密一个文件,然后允许授权用户查看它而不保存解密的文件。这是为了确保其他用户无法打开解密的文件 以下代码生成了一个文件输出 public NewJFrame() {try{ String key = "squirrel123"; FileInputStream fis2 = newFileInputStream("encrypted.mui"); FileOutputS
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的情况下解密文件,然后允许授权用户在解密后查看该文件?如果您不想将其写入物理文件,而只是显示数据,则可以使用不同的编写器,然后使用FileOutputStream 例如,您可以创建一对管道流,解密然后读取结果
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);
}
您能否使用内存中的输出流之一,例如ByteArrayOutputStream作为您的输出流?抱歉,我无法记住Java从那里到字符串的奇怪流轨迹。这将允许您在不必接触磁盘的情况下解密和显示。那么就不可能通过继承、覆盖和类折叠(Groovy)来“窃取”您的秘密或“查看”之类的方法。您也可以使用ByteArrayOutputStream。@Netto我也遇到了同样的问题,但我不知道我可以将BufferedReader代码放在哪里。你能帮我吗?@felipecrp我也有同样的问题,你能帮我吗me@KVK“BufferedReader放在哪里”是什么意思?一个像管道一样的流,你可以在这里放置或读取信息。读卡器是处理流的低级功能的实体,因此您不必担心读取字节和长度的数组。本主题的重点是使用不同的输出流,然后是“FileOutputStream”,因此您不需要编写另一个文件,而是直接解析de数据。