In: Computer Science
Problem
1. Write two computer programs to simulate a Unicode stream
cipher that consists of both
encryption and decryption algorithms. The encryption program
accepts inputs from an
existing text file, called “letter.txt.” The encryption program
produces an output ciphertext
file, called “secret” The decryption program takes “secret” as
input and decrypts it into a
plaintext, called “message.txt.”
- The random “seed” must be known, but be kept secure, by the
pseudorandom number
generators in both encryption and decryption programs.
Note from me: Use Java.
PROGRAM :
//EncryptDecrypt.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
public class EncryptDecrypt{
public static void main(String[] args) {
try{
//Generate private key............
KeyGenerator key_generator = KeyGenerator.getInstance("DES");
SecretKey myPrivateKey = key_generator.generateKey();
Cipher cipher;
cipher = Cipher.getInstance("DES");
//Read text from a file named letter.txt
String data = "";
try {
File readFile = new File("/Users/hari-mohan/Desktop/files/letter.txt");
Scanner sc = new Scanner(readFile);
while (sc.hasNextLine()) {
data = sc.nextLine();
}
System.out.println("Read data successfully.");
sc.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
//Encrypt the data................
byte[] byteData = data.getBytes("UTF8");
cipher.init(Cipher.ENCRYPT_MODE, myPrivateKey);
byte[] dataEncrypted = cipher.doFinal(byteData);
String s = new String(dataEncrypted);
System.out.println(s);
//Write the encrypted data into the file named secret.txt
try {
FileWriter fileWriter = new FileWriter("/Users/hari-mohan/Desktop/files/secret.txt");
fileWriter.write(s+"");
System.out.println("Write encrypted data successfully.");
fileWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
}
//Decrypt the data................
cipher.init(Cipher.DECRYPT_MODE, myPrivateKey);
byte[] textDecrypted = cipher.doFinal(dataEncrypted);
s = new String(textDecrypted);
System.out.println(s);
//Write decrypted data into the file named message.txt
try {
FileWriter fileWriter = new FileWriter("/Users/hari-mohan/Desktop/files/message.txt");
fileWriter.write(s+"");
System.out.println("Write original data successfully.");
fileWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
}
}catch(Exception e)
{
System.out.println("Exception"+e.getMessage());
}
}
}