gpt4 book ai didi

java - 如何在没有文件输出的情况下用Java显示解密文件?

转载 作者:行者123 更新时间:2023-11-30 11:10:08 25 4
gpt4 key购买 nike

我正在尝试开发一个系统,该系统将解密一个文件,然后允许授权用户在不保存解密文件的情况下查看它。这是为了确保其他用户无法打开解密后的文件。

以下代码产生了一个文件输出。

    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 不同的编写器。

比如可以创建一对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);
}

关于java - 如何在没有文件输出的情况下用Java显示解密文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com