我正在阅读关于使用私钥进行加密的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"));
}
}
上面的代码很好用。我能够看到结果和一切。但我想修改它如下,以便我可以将cipherText存储在文件中。然后另一个程序从文件中读取加密的文本并对其进行解密。以下是我迄今为止所做的,但我无法理解如何继续。只有一点点提示如何进行将有所帮助。
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