2015-01-08 1 views
2

파일을 해독하는 시스템을 개발하려고하는데, 권한이 부여 된 사용자가 해독 된 파일을 저장하지 않고 볼 수 있습니다. 이는 다른 사용자가 해독 된 파일을 열 수 없도록하기위한 것입니다.해독 된 파일을 파일 출력없이 Java로 표시하는 방법은 무엇입니까?

다음 코드는 파일 출력을 생성했습니다.

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에 다음 권한이 부여 된 사용자가 암호 해독 후를 볼 수 있습니다 사용하지 않고 파일의 암호를 해독 할 수 있습니까?

+2

출력 스트림에 대해 ByteArrayOutputStream과 같은 메모리 내 OutputStream 중 하나를 사용할 수 있습니까? 죄송합니다. Java에서 이상한 스트림 산책로를 거기에서 문자열로 옮기는 것을 기억할 수 없습니다. 그러면 디스크를 만지지 않아도 해독하고 표시 할 수 있습니다. – Rob

+0

Okey. 감사. :) –

답변

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); 
     } 
+2

이 클래스를 최종 작성해야한다는 것에 주목하십시오. 그런 다음 상속, 덮어 쓰기 및 클래스 폴딩 (Groovy)으로 "보기"와 같은 비밀 또는 메서드를 "도용"하는 것은 불가능합니다. – tfb785

+0

ByteArrayOutputStream을 사용할 수도 있습니다. – felipecrp

+0

@Netto 나는 또한 같은 문제가 있지만 어디 BufferedReader 코드를 넣을 수 있는지 모르겠습니다. 너 나 좀 도와 줄 수있어? – KVK

관련 문제