Answer:
C code is given below
Step-by-step explanation:
// Vigenere cipher
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* Reading key file.
*/
char *readFile(char *fileName) {
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL) return NULL; //could not open file
code = (char *)malloc(513);
while ((c = fgetc(file)) != EOF) {
if( !isalpha(c) )
continue;
if( isupper(c) )
c = tolower(c);
code[n++] = (char)c;
}
code[n] = '\0';
fclose(file);
return code;
}
int main(int argc, char ** argv){
// Check if correct # of arguments given
if (argc != 3) {
printf("Wrong number of arguments. Please try again.\\");
return 1;
}
// try to read the key file
char *key = readFile(argv[1]);
if( !key ) {
printf( "Invalid file %s\\", argv[1] );
return 1;
}
char *data = readFile(argv[2]);
if( !data ) {
printf("Invalid file %s\\", argv[2] );
return 1;
}
// Store key as string and get length
int kLen = strlen(key);
int dataLen = strlen( data );
printf("%s\\", key );
printf("%s\\", data );
int paddingLength = dataLen % kLen;
if( kLen > dataLen ) {
paddingLength = kLen - dataLen;
}
for( int i = 0; i < paddingLength && dataLen + paddingLength <= 512; i++ ) {
data[ dataLen + i ] = 'x';
}
dataLen += paddingLength;
// Loop through text
for (int i = 0, j = 0, n = dataLen; i < n; i++) {
// Get key for this letter
int letterKey = tolower(key[j % kLen]) - 'a';
// Keep case of letter
if (isupper(data[i])) {
// Get modulo number and add to appropriate case
printf("%c", 'A' + (data[i] - 'A' + letterKey) % 26);
// Only increment j when used
j++;
}
else if (islower(data[i])) {
printf("%c", 'a' + (data[i] - 'a' + letterKey) % 26);
j++;
}
else {
// return unchanged
printf("%c", data[i]);
}
if( (i+1) % 80 == 0 ) {
printf("\\");
}
}
printf("\\");
return 0;
}