2013-03-28 15 views
0

개인 키를 사용하여 암호화하는 방법에 대한 IBM 자습서를 진행했습니다. 아래 코드를 작성했습니다.파일에서 암호화 된 데이터 읽기

import java.security.*; 
import javax.crypto.*; 

// encrypt and decrypt using the DES private key algorithm 

public class PrivateExample { 

    public static void main (String[] args) throws Exception { 
    String text=new String(); 
    text="THIS IS AN ENCRYPTION TEST"; 
    byte[] plainText = text.getBytes("UTF8"); 

    // get a DES private key 
    System.out.println("\nStart generating DES key"); 
    KeyGenerator keyGen = KeyGenerator.getInstance("DES"); 
    keyGen.init(56); 
    Key key = keyGen.generateKey(); 
    System.out.println("Finish generating DES key"); 

    // get a DES cipher object and print the provider 
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); 
    System.out.println("\n" + cipher.getProvider().getInfo()); 
    // 
    // encrypt using the key and the plaintext 
    System.out.println("\nStart encryption"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    byte[] cipherText = cipher.doFinal(plainText); 
    System.out.println("Finish encryption: "); 
    System.out.println(new String(cipherText, "UTF8")); 

    // 
    // decrypt the ciphertext using the same key 
    System.out.println("\nStart decryption"); 
    cipher.init(Cipher.DECRYPT_MODE, key); 
    byte[] newPlainText = cipher.doFinal(cipherText); 
    System.out.println("Finish decryption: "); 

    System.out.println(new String(newPlainText, "UTF8")); 
    } 
} 

위의 코드는 훌륭합니다. 결과와 모든 것을 볼 수 있습니다. 하지만 나는 암호문을 파일에 저장할 수 있도록 다음과 같이 수정하고 싶다. 그런 다음 다른 프로그램이 파일에서 암호화 된 텍스트를 읽고 해독합니다. 아래는 지금까지 해 온 것이지만 진행 방법을 이해할 수는 없습니다. 진행 방법에 대한 약간의 힌트가 도움이 될 것입니다.

import java.security.*; 
import javax.crypto.*; 

// encrypt and decrypt using the DES private key algorithm 
public class PrivateExample { 

    public static void main (String[] args) throws Exception { 
    String text=new String(); 
    text="This is an encryption test"; 

    byte[] plainText = text.getBytes("UTF8"); 

    // get a DES private key 
    System.out.println("\nStart generating DES key"); 
    KeyGenerator keyGen = KeyGenerator.getInstance("DES"); 
    keyGen.init(56); 
    Key key = keyGen.generateKey(); 
    System.out.println("Finish generating DES key"); 
    // 
    // get a DES cipher object and print the provider 
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); 
    System.out.println("\n" + cipher.getProvider().getInfo()); 
    // 
    // encrypt using the key and the plaintext 
    System.out.println("\nStart encryption"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    byte[] cipherText = cipher.doFinal(plainText); 
    System.out.println("Finish encryption: "); 
    System.out.println(new String(cipherText, "UTF8")); 

    //Now writing to an ouput file the cipherText 
    try{ 
     FileOutputStream fs=new FileOutputStream("c:/test.txt"); 
     fs.write(cipherText); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
//How to proceed from here 

} 
} 

이제이 프로그램의 작업이 완료되었습니다. 암호화 된 문자열을 파일에 성공적으로 기록했습니다. 새 프로그램은 데이터를 해독하면됩니다. 파일에서 암호화 된 바이트를 읽으려면 어떻게해야합니까? 새로운 프로그램은 원래 문자열이 무엇인지에 대해서는 전혀 몰랐지만 알고리듬과 같은 키를 사용할 것입니다. 도와주세요! 나는 다음은 파일에 키를 작성하는 방법의 암호화

+0

그럼 파일로 읽어 들이기 만하면됩니까? –

+0

키를 파일에 저장하고 암호 해독에 사용합니다. – user1516873

+2

'key'는 프로그램이 끝나기 전에 저장하지 않으면 매우 사적인 것입니다. – Anthon

답변

2

새로운 오전 :

 //Write your key to an output file. 
     byte[] keyAsByte = key.getEncoded(); 
     FileOutputStream keyfos = new FileOutputStream("key.txt"); 
     keyfos.write(keyAsByte); 
     keyfos.close(); 

나는 같은 파일의 암호화 된 텍스트로 키를 넣어 권하고 싶지 않다.

//Read your key 
    FileInputStream keyFis = new FileInputStream("key.txt"); 
    byte[] encKey = new byte[keyFis.available()]; 
    keyFis.read(encKey); 
    keyFis.close(); 
    Key keyFromFile = new SecretKeySpec(encKey, "DES"); 
    //Read your text 
    FileInputStream encryptedTextFis = new FileInputStream("test.txt"); 
    byte[] encText = new byte[encryptedTextFis.available()]; 
    encryptedTextFis.read(encText); 
    encryptedTextFis.close(); 
    //Decrypt 
    Cipher decrypter = Cipher.getInstance("DES/ECB/PKCS5Padding"); 
    decrypter.init(Cipher.DECRYPT_MODE, keyFromFile); 
    byte[] decryptedText = decrypter.doFinal(encText); 
    //Print result 
    System.out.println("Decrypted Text: " + new String(decryptedText)); 

을 : 여기

는 다시 ecrypted 텍스트와 키를 읽고 해독 방법은 내가 정보를 작성하기위한 당신과 같은 경로를 사용하지 않았다.

+0

도움을 주셔서 대단히 감사합니다. –

+0

의심의 여지가 하나 더 있습니다. 값을 다시 읽은 다음 패딩을 얻을 수도 있습니다. 패딩을 쉽게 제거 할 수있는 방법이 있습니까? –

+0

해독 된 텍스트를 채우고 싶습니까? – nattyddubbs