Random monoalphabet cipher. The Caesar cipher, which shifts all letters by a fix
ID: 3624829 • Letter: R
Question
Random monoalphabet cipher. The Caesar cipher, which shifts all letters by a fixed amount, is far too easy to crack. Here is a better idea. For the key, don't use numbers but words. Suppose the key word is FEATHER. Then first remove duplicate letters, yielding FEATHR, and append the other letters of the alphabet in reverse order. Now encrypt the letters as follows:
Write a program that encrypts or decrypts a file using this cipher. The key word is specified with the -k command line option. The -d command line option specifies decryption. For example:
decrypts a file using the keyword FEATHER. It is an error not to supply a keyword.
Explanation / Answer
import java.lang.String;
import java.io.*;
public class Encryptor {
public static void main(String[] args) throws Exception
{
String alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//
{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
String replacestr;
String inputString=args[1];
inputString=inputString.toUpperCase();
String fname=args[2];
inputString = inputString.replaceAll((String.format("(.)(?<=(?:(?=\1).).{0,%d}(?:(?=\1).))",
inputString.length())), "");
replacestr=inputString;
System.out.println(alphabets);
for(int i=25;i>=0;i--)
{
replacestr +=alphabets.charAt(i);
}
replacestr = replacestr.replaceAll((String.format("(.)(?<=(?:(?=\1).).{0,%d}(?:(?=\1).))",
replacestr.length())), "");
System.out.println(replacestr);
try
{
FileInputStream fstream = new FileInputStream(fname);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String Data="";
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
Data=Data+strLine;
// Print the content on the console
System.out.println (strLine);
}
Data=Data.toUpperCase();
if(args[0].equalsIgnoreCase("-k"))
{
for(int i=0;i<26;i++)
{
Data=Data.replace(alphabets.charAt(i),replacestr.charAt(i));
}
System.out.println();
System.out.println(Data);
}
else if(args[0].equalsIgnoreCase("-d"))
{
for(int i=0;i<26;i++)
{
Data=Data.replace(replacestr.charAt(i),alphabets.charAt(i));
}
System.out.println();
System.out.println(Data);
}
BufferedWriter out = new BufferedWriter(new FileWriter(args[3]));
out.write(Data);
out.close();
//Close the input stream
in.close();
}
catch(FileNotFoundException fnfe)
{
System.out.println(""+fnfe);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.