PROGRAM CAN BE WRITE IN C OR JAVA In this assignment you\'ll write a program tha
ID: 3849847 • Letter: P
Question
PROGRAM CAN BE WRITE IN C OR JAVA
In this assignment you'll write a program that encrypts the alphabetic letters in a file using the Hill cipher where the Hill matrix can be any size from 2 x 2 up to 9 x 9. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below.
Command Line Parameters
Your program must compile and run from the command line.
The program executable must be named “hillcipher” (all lower case, no spaces or file extension).
input the required file names as command line parameters. Your program may NOT prompt the user to enter the file names. The first parameter must be the name of the encryption key file, as described below. The second parameter must be the name of the file to be encrypted, as also described below. The sample run command near the end of this document contains an example of how the parameters will be entered.
Your program should open the two files, echo the input to the screen, make the necessary calculations, and then output the ciphertext to the console (terminal) screen in the format described below.
Note: If the plaintext file to be encrypted doesn't have the proper number of alphabetic characters, pad the last block as necessary with the letter 'X'. (Yes, this is different from what is in our class slides, but it is necessary for us to do this so we can know what outputs to expect for our test inputs.
Encryption Key File Format
The encryption key file will store a single positive integer, n (1 < n < 10), on the first line, indicating the number of rows and columns in the encryption matrix. The following n lines will contain the contents of each row, in order, of the encryption matrix, separated by spaces.
Format of the File to be Encrypted
The file to be encrypted can be any valid text file with no more than 9991 letters in it. (Thus, it's safe to store all characters in the file in a character array of size 10000, including any padding characters.) Please note that the input text file will also generally have punctuation, numbers, special characters, and whitespace in it, which should be ignored. You should also ignore whether a letter is uppercase or lowercase in the input file. Thus, you should treat ‘A’ and ‘a’ the same in your program.
Output Format
The program must output the following to the console (terminal) screen:
Echo the input key file
Echo the input plaintext file
Ciphertext output produced from running the cipher against the input plaintext file.
The ciphertext output portion should consist of only lowercase letters in rows of exactly 80 letters per row, except for the last row, which may possibly have fewer. These characters should correspond to the ciphertext produced by encrypting all the letters in the input file. Please note that only the alphabetic letters in the input plaintext file will be encrypted. All other characters should be ignored.
What to Turn In over WebCourses
You must submit this assignment in the form specified at the top of this assignment.
Program Notes and Hints
Your program must read in an input plaintext file that may contain uppercase letters, lowercase letters and non-letter characters. Your program must distinguish between these three groups so that only the letters get encrypted. All non-letter characters in the file are simply skipped and not counted as part of the plaintext. Please note that although both upper case and lower case letters will be encrypted, your program should not treat them differently, that is, the program should process an upper case input letter the same as the corresponding lower case letter, i.e., it should treat an ‘A’ the same as an ‘a’.
One possible breakdown to solve this problem is as follows:
1) Write a section of code or function that reads only the upper and lower case letters in the input file into an char array of size 10000, storing only the appropriate lowercase letters in the character array.
2) Write a section of code or function that takes as input the array from section 1 and the encryption key and produces an array of ciphertext storing only lowercase letters.
3) Write a section of code or function that takes as input the array storing the ciphertext and outputs it to the screen in the format specified. Additional functions or code will be needed to echo the input key and plaintext files.
Sample Key File
4
9 12 13 1
7 3 6 9
8 4 2 1
10 5 15 3
Sample Input File
Security professionals have said for years that the only way to make a computer truly secure is for it to not be connected to any other computers, a method called airgapping. Then, any attack would have to happen physically, with the attacker actually entering the room and accessing the computer that way, which is incredibly unlikely. In the case of computers containing highly sensitive information, additional, physical security can always be added in the form of security guards, cameras, and so on.
Researchers at Georgia Institute of Technology have uncovered a vulnerability in all computers, however, which can be exploited regardless of an air gap. It’s a vulnerability which you’d never suspect, and it’s one that’s hard to fight against. All CPUs emit electromagnetic signals when they are performing tasks, and the first thing these researchers discovered was that binary ones and zeroes emit different levels. The second thing they discovered is that electromagnetic radiation is also emitted by the voltage fluctuations and that it can be read from up to six meters away. These signals, by the way, are known as side-channels, and they are well-documented in the cryptography field.
Corresponding Output File
wsceafwvgznsacsihctehylsayiyanlevvrznraqaimmhdcajbjnuqowykyivehgkiztslktzvtlhxbb
lehmcpoddwkbnrmwpszcognnoxhsujopvehggfgfunbegpydafnalyubtzumbaryxctoolpkueyssrjy
cdyhojobqftmdqgbdfftfpcmptrlqblscygqqqdxwtlikntstkzynvmmvpysnfggiyyorwarxoifrocr
rcncuxmfjhrdnuqlnmwfonkzfaqrzcsxurclysqewceqsrudvehgixiljruwhapsojuzfyktsnyjyhwl
vrkceovbtuqheptotuqheqeyygyqfrognudutffdcjkvhektblwuzixkijszqyjnwsceafwvzvpdjjwu
nqqfwxruffhfxpkedwbggfgfxpqkrduinkpehormclniilpmejihjohafckdfanspsnorbauspqbypan
fmxwfpgccdibgdcrdqevwnmtyvwhdyqzyiusrivktliuywsytxpbihilgmtlonudnaxuhkxypwnahkql
mtcpzdugihctxighzgbyyjitpujkqnitbwpwwrsvvvkqpzzllwxwapqpkwkocnmxnnkwrdrpgvwblrtl
ybybnynehxqikxelwhtopgejztqwwxruaplojwfyihbunvmmtqqztfvrperkihifvkobcjypcxngpfie
ytgpolihmwfdkrcjkwkoebdcgdqzyqymixqhncybvbdnqksubaryhimvzptvjahmwbzifyrgmprwqgkk
edkrrojkpigzojqpqhqdrxlrzqtytrakzkfizjlbuijltoypwlshrrfjnqhmgxrkgzedkeooqpribrpd
rmyvbhwowplkkiakbwktopebrmcntrjpbcipirmbpwerlwfqotefguzlhxqixnsmyuwscauakrjiomfj
tounfowfrmrauhyhppnt
Sample Run Command
C or C++ program:
prompt> ./hillcipher spr17Key4.txt hill-17spring-01
Java program:
prompt> java hillcipher spr17Key4.txt hill-17spring-01
Grading Rubric
The total possible score for this program is 100 points. The following point values will be deducted for the reasons stated:
[ -100 points ] Your program does not successfully compile from the command line with one of these commands:
C program: prompt> gcc –o hillcipher [your_file_name].c
C++ program: prompt> g++ –o hillcipher [your_file_name].cpp
Java program: prompt> javac hillcipher.java
Note: If you are submitting a Java program, the class file must be named “hillcipher.java” and the class name must be “hillcipher”.
[ -90 points ] Your program does not run from the command line without error or produces no output.
[ -70 points ] The program compiles, runs, and outputs the key matrix and input file, but crashes thereafter or produces no encryption output.
[ -50 points ] The program compiles, runs, echoes the inputs, and generates encryption output, but the encryption output is incorrect (ignoring case) and it is not formatted correctly (not all letters or not all lowercase or not 80 letters per line).
[ -25 points ] The program compiles, runs, echoes the inputs, generates encryption output, and the encryption output is correct (ignoring case), but it is formatted incorrectly (not all letters or not all lowercase or not 80 letters per line).
[ -25 points ] The program compiles, runs, echoes the inputs, and generates encryption output, but the encryption output is incorrect (ignoring case) although it is formatted correctly (all lowercase letters, 80 letters per line).
[ no deductions ] The program compiles, runs, echoes the inputs, generates encryption output, the encryption output is correct (ignoring case), and it is formatted correctly (all lowercase letters, 80 letters per line).
PROGRAM SHOULD LOOK LIKE THIS
mmc@d7 bash 97x45 5spring java hillcipher spr txt hill-15spring-01 r15Ke Key matrix 12 13 7 3 6 9 8 4 2 1 10 5 15 3 Plaintext security professionalshavesaidforyearsthattheonlywaytomakeacomputertrulysecureisf or ittonotbeconnectedtoanyothercomputersamethodcalledairgappingthenanyattackwould havetohappenphysicallywiththeattackeractuallyente ringt heroornandaccessingthecompu terthatwaywhichis incredibly unlikely inthecaseofcomputerscontaininghighlysensitive informationadditionalphysicalsecuritycanalways beaddedintheform of securityguardsca merasandsoonresearchersatgeorgiainstituteoftechnologyhaveuncoveredavulnerability inallcomputershoweverwhichcanbeexploited regardlessofanairgapitsavulnerabilitywhi chyoudneversuspectand itsonethatshardtofightagainstallcpusemitelect romagneticsign als whenthey are performingtasks andthefirstthingthese researchersdiscoveredwas thatbi na ryone sandze roesemitdifferentlevelsthesecondthingtheydiscoveredisthat electromag netic canber me tersawaythesesignalsbythewaya reknownassidechannelsandtheya rewelldocumentedinth ecryptographyfieldxx Ciphertext ws ceafwwgznsacsihcte hylsayiyanlevvrznra gaimmhdcaj bjnuqowykyivehgkiztslkt z vtlhxbb lehmcpoddwkbn rmwpszcognnoxhsujopvehggfgfunbegpydafnalyubtzumbaryxctoolpkueyss rjy cdyho jobqftmdqgbdfftfpcm pt r lqbliss cygqqqdxwtt likntstkzynvmmvpysnfggiyyorwarxoifrocr rcncuxm fjhrdnuqunmwfonkzfaqrzcsxurclys qewcegs rudvehgixilji ruwhaps oj uz fyktsnyj yhwl vrkceovbtugheptotugheqeyygyqf rognu du ffdcjkvhektblwuzixkijszqyjnws cea fwvzvpdijwu nqqfwx ruffhfxpkedwbggfgfxpqk reduinkpeho rm clni ilpmejihjohafckdfanspsnorbauspqbypan fmxwfpgccdibgdcrdqevwnmtyvwhdyqzyius rivktliuywsytxpbihilgmt lonudnaxuhkxypwnahkql ybybnynehxgikxelwhtopgeji ztqwwx ruaplojwfyihbunv mmteqqztfvrperkihifvkobcj ypcxngpfie ytgpolihmwfdkrecj kwkoebdcgdqzyqymixqhncybvbdnqksuba ryhimvzptvjahmwbzifyrgmprwagkk edkrroj kpig zojqpqhqdrxlrzqtyt rakzkfizjubuijutoypwlshrrfjnqhmgxrkgzedkeooqpribrpd rmyvbhwowplkkiakbwktopebr mcnt injpbcipirmb pwerlwfgotefgu z lhxqixnsmyuwscauakrjiomfj tounfowfrm rauhyhppnt [561] michaelmcalpin@Hydrogen /data/Business/UCF/2015-Spring/CIS3360-MMc/Assignments/prog1/hill-1 springExplanation / Answer
//hillcipher.java
==============================================================
import java.io.FileNotFoundException;
public class hillcipher {
static char[] finalGrid;
public static void main(String[] args) throws FileNotFoundException
{
// grab file names for key and plaintext its assumed they are located in same directory as src files
String keyLocation = args[0];
String messageLocation = args[1];
// create new object for key and message based on files
Key inKey = new Key(keyLocation);
Message message = new Message(messageLocation,inKey);
//print key
inKey.printKey();
System.out.println();
//print plaintext
message.printPlainText();
//run the encryption method
encrypt(inKey,message);
//print cipherText
System.out.println();
System.out.println();
printCiphertext();
System.out.println();
}
public static void encrypt(Key key, Message message) {
// go through converted message split into chunks of the key size
// multiply these chunks by the key mod each result by 26
// result into a char array finalGrid
//temp will store the chunks of the plaintext that will be multipled by key
int[][] temp = new int[key.size][1];
//product will hold the product of the matrix multiplication between key and message chunks
int[][] product = new int[key.size][1];
//instantiate finalGrid this will hold our ciphertext as a char array
finalGrid = new char[message.convertedMessage.length];
int findex = 0;
//loop through message char array
//we are adding key.size to i each time so we get the correct size chunk to multiply with
for (int i = 0 ; i < message.convertedMessage.length ; i = i + key.size ) {
//populate the temp array with chunks
for (int j = 0 ; j < key.size ; j++ ) {
temp[j][0] = message.convertedMessage[i+j][0];
}
product = multiply(key.grid,temp);
//take product and add it to the final char array
//being sure to mod each result by 26 and convert back to a letter
for ( int k = 0 ; k < key.size ; k++ ) {
finalGrid[findex] = Utility.findLetter(product[k][0] % 26);
// we do not want the index of finalGrid to restart every iteration of the larger loop
// so I added its own index counter
findex++;
}
}
}
// return C = A * B
// gotten from http://introcs.cs.princeton.edu/java/22library/Matrix.java.html
public static int[][] multiply(int[][] A, int[][] B) {
int mA = A.length;
int nA = A[0].length;
int mB = B.length;
int nB = B[0].length;
if (nA != mB) throw new RuntimeException("Illegal matrix dimensions.");
int[][] C = new int[mA][nB];
for (int i = 0; i < mA; i++)
for (int j = 0; j < nB; j++)
for (int k = 0; k < nA; k++)
C[i][j] += (A[i][k] * B[k][j]);
return C;
}
public static void printCiphertext() {
System.out.println("Ciphertext: ");
//output must be 80 char per line
// we start at 1 so the first line of output is 80 characters
// as well as all of the following lines
for ( int i = 1 ; i < finalGrid.length+1 ; i++ ) {
if ( (i % 80) == 0 && i != 0 ) {
System.out.println(""+finalGrid[i-1]);
}
else {
System.out.print(""+finalGrid[i-1]);
}
}
}
}
=====================================================================
//Utility.java
public class Utility {
public static int findAlphaIndex(char c) {
switch (c) {
case 'a':
return 0;
case 'b':
return 1;
case 'c':
return 2;
case 'd':
return 3;
case 'e':
return 4;
case 'f':
return 5;
case 'g':
return 6;
case 'h':
return 7;
case 'i':
return 8;
case 'j':
return 9;
case 'k':
return 10;
case 'l':
return 11;
case 'm':
return 12;
case 'n':
return 13;
case 'o':
return 14;
case 'p':
return 15;
case 'q':
return 16;
case 'r':
return 17;
case 's':
return 18;
case 't':
return 19;
case 'u':
return 20;
case 'v':
return 21;
case 'w':
return 22;
case 'x':
return 23;
case 'y':
return 24;
case 'z':
return 25;
default:
return 99;
}
}
public static char findLetter(int c) {
switch (c) {
case 0:
return 'a';
case 1:
return 'b';
case 2:
return 'c';
case 3:
return 'd';
case 4:
return 'e';
case 5:
return 'f';
case 6:
return 'g';
case 7:
return 'h';
case 8:
return 'i';
case 9:
return 'j';
case 10:
return 'k';
case 11:
return 'l';
case 12:
return 'm';
case 13:
return 'n';
case 14:
return 'o';
case 15:
return 'p';
case 16:
return 'q';
case 17:
return 'r';
case 18:
return 's';
case 19:
return 't';
case 20:
return 'u';
case 21:
return 'v';
case 22:
return 'w';
case 23:
return 'x';
case 24:
return 'y';
case 25:
return 'z';
default:
return (Character) null;
}
}
}
===================================================================
//Message.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Message {
String fullMessage;
String strFinalMessage;
char[] finalMessage;
int[][] convertedMessage;
char[] cipherMessage;
public Message(String inFile, Key key) throws FileNotFoundException {
//set up two local string variables for use in this method
String scanMessage = "";
String result = "";
// Open the file for reading save full message
Scanner scanner = new Scanner(new File(inFile));
while (scanner.hasNextLine()) {
scanMessage += scanner.nextLine();
}
//take out everything but letters and set to lowercase characters
result = scanMessage.replaceAll("[^\p{Alpha}]+","").replaceAll("\s+", "+").toLowerCase();
this.strFinalMessage = result;
int pad = result.length() % key.size;
// find out if message needs padding or not
// if it does then we need to instanciate a larger version than just the result.length
if ( pad != 0 ) {
this.finalMessage = new char[result.length()+pad];
//keep adding padding until its no longer needed
while (result.length() % key.size != 0) {
result += 'x';
}
}
else {
this.finalMessage = new char[result.length()];
}
//set our class variable strFinal with this new finished string
this.strFinalMessage = result;
//turn final string into char array
this.finalMessage = result.toCharArray();
//create converted array full of index representation of letters
convertMessage();
scanner.close();
}
public void printPlainText() {
System.out.println("Plaintext: ");
//output must be 80 char per line
for ( int i = 1 ; i < this.finalMessage.length ; i++ ) {
if ( (i % 80) == 0 && i != 0 ) {
System.out.println(""+this.finalMessage[i-1]);
}
else {
System.out.print(""+this.finalMessage[i-1]);
}
// old code used to visualze the chunks to make sure it was padded correctly
// what i is modded by is a hard coded value of the key size
/*if (i % 4 == 0) {
System.out.print("|");
}*/
}
}
public void convertMessage() {
this.convertedMessage = new int[this.finalMessage.length][1];
//simply go through the message and swap the char for their corrisponding index
for ( int i = 0 ; i < finalMessage.length ; i++ ) {
this.convertedMessage[i][0] = Utility.findAlphaIndex(this.finalMessage[i]);
}
}
public void printCipherText() {
System.out.println("Ciphertext: ");
//output must be 80 char per line
for ( int i = 1 ; i < this.cipherMessage.length+1 ; i++ ) {
if ( (i % 80) == 0 && i != 0 ) {
System.out.println(""+this.cipherMessage[i-1]);
}
else {
System.out.print(""+this.cipherMessage[i-1]);
}
}
}
}
============================================================================
//Key.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Key {
int size;
int[][] grid;
public Key(String keyFile) throws FileNotFoundException {
// Open the file for reading
Scanner scanner = new Scanner(new File(keyFile));
// Get size of matrix will always be a square matrix
this.size = scanner.nextInt();
// Allocate the grid.
this.grid = new int[size][size];
// Iterate through the rows.
for( int row = 0 ; row < this.size ; row++ )
{
// Iterate through the columns.
for( int column = 0; column < this.size ; column++ )
{
// Read each value
this.grid[row][column] = scanner.nextInt();
}
}
scanner.close();
}
public void printKey() {
//same as all other print methods
System.out.println("Key Matrix: ");
for( int row = 0 ; row < this.size ; row++ )
{
for( int column = 0; column < this.size ; column++ )
{
if ( column == this.size-1 ) {
System.out.println(this.grid[row][column]);
}
else {
System.out.print(this.grid[row][column]+" ");
}
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.