개인 키를 사용하여 암호화하는 방법에 대한 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
}
}
이제이 프로그램의 작업이 완료되었습니다. 암호화 된 문자열을 파일에 성공적으로 기록했습니다. 새 프로그램은 데이터를 해독하면됩니다. 파일에서 암호화 된 바이트를 읽으려면 어떻게해야합니까? 새로운 프로그램은 원래 문자열이 무엇인지에 대해서는 전혀 몰랐지만 알고리듬과 같은 키를 사용할 것입니다. 도와주세요! 나는 다음은 파일에 키를 작성하는 방법의 암호화
그럼 파일로 읽어 들이기 만하면됩니까? –
키를 파일에 저장하고 암호 해독에 사용합니다. – user1516873
'key'는 프로그램이 끝나기 전에 저장하지 않으면 매우 사적인 것입니다. – Anthon