#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <stdlib.h>
#include <ctype.h>
int CheckArgs(int argc, char *argv[])
{
unsigned char *prog = argv[0];
if(argc != 3)
{
fprintf(stdout, "ERROR: %s requires plain and cipher file arguements.n", prog);
return 0;
}
else
return 1;
}
unsigned int GetFileLen(FILE *fp)
{
unsigned int len = 0;
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
fseek(fp, 0L, SEEK_SET);
return len;
}
int main(int argc, char *argv[])
{
FILE *infile;
FILE *outfile;
unsigned char key[26];
unsigned char *data;
unsigned int datalen;
unsigned int i = 0;
unsigned int j = 0;
unsigned int temp = 0;
printf("nMonoAplhabetic Substitution Cipher by typedeaF @
www.osix.netn");
if(!CheckArgs(argc, argv))
{
return EXIT_FAILURE;
}
if((infile = fopen(argv[1], "rb")) == NULL)
{
fclose(infile);
printf("ERROR: %s could not open %s for reading.n", argv[0], argv[1]);
return EXIT_FAILURE;
}
if((outfile = fopen(argv[2], "wb")) == NULL)
{
fclose(infile), fclose(outfile);
printf("ERROR: %s could not open %s for writing.n", argv[0], argv[2]);
return EXIT_FAILURE;
}
if((keyfile = fopen("key.txt", "wb")) == NULL)
{
fclose(infile), fclose(outfile);
printf("ERROR: %s could not open keyfile for writing.n", argv[0], argv[2]);
return EXIT_FAILURE;
}
datalen = GetFileLen(infile);
if((data = malloc(datalen)) == NULL)
{
fclose(infile), fclose(outfile), free(data);
printf("ERROR: Insuffecient Memoryn");
return EXIT_FAILURE;
}
if(!fread(data, datalen, 1, infile))
{
fclose(infile), fclose(outfile), free(data);
printf("ERROR: read error.n");
return EXIT_FAILURE;
}
/* initilize key */
for(i = 0; i < 26; i++)
{
key[i] = i + 'a';
}
srand((unsigned)time(NULL));
/* shuffle the key */
for(i = 0; i < 26; i++)
{
j = (unsigned int)((26) * (rand() / ((double)RAND_MAX + 1.0)));
temp = key[i];
key[i] = key[j];
key[j] = temp;
}
/* save the key */
for(i = 0; i < 26; i++)
putc(key[i], keyfile);
printf("nProcessing");
for(i = 0;(unsigned int)i < datalen; i++)
{
printf(".");
fflush(stdout);
if(isalpha(data[i]))
fputc(key[tolower(data[i])-'a'], outfile);
else
fputc(data[i], outfile);
}
printf("nDONE");
fclose(infile), fclose(outfile), free(data);
return EXIT_SUCCESS;
}