Search code examples
cencryptionxor

How to encrypt a text file using bit-wise XOR?


I am trying to encrypt a message from a text file by using the bit-wise XOR operation on the left and right characters with two specific keys from another file(keys.txt), but I am receiving unreadable code in front of the original text file(nothing changed), which is not right. I am using two text files:

1) Input.txt - containing the message that is to be encrypted

2) Keys.txt - This contains two characters that do the XOR operation to each character in the input.txt (character 1 is key 1 and character 2 is key 2)

The following code in my program:

str[i]=str[i]^str2[2];
str[++i]=str[i]^str2[1];
break;

is the line of code that is suppose to be performing the XOR operation

Note My desired output should look similar to this:

m@#EmI(>9S(@)H#FmN# XGmmmmU,H!Gmr(DmI"VmD,F(S!XmU%DmM"C>U(S>,O)9I(9T?U!D>,M!,E;@#B(Gmu%D4,S(:@$U$O*"OmU%DmR%H#F!D`V$M!4N8.N Dm@#EmK"H#9I(+mmmm)@#B(f

Can someone clarify the issue that I am running into?

The user should enter:

gcc myProgram.c
./a.out e input.txt keys.txt

(The e just stands for encryption)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int main(int args, char *argc[]){

int i;
int len=0;
char str[1024];
char str2[2];
FILE *finp;
FILE *keyFile;

if ( strcmp(argc[1], "e") == 0 )
{
  if ( (finp = fopen(argc[2],"r")) == NULL )
  {
    printf("Could Not Open file %s\n", argc[2]);
    exit(1);
  }

  if ( (keyFile = fopen(argc[3],"r")) == NULL )
  {
    printf("Could Not Open file %s\n", argc[3]);
    exit(1);
  }


  while((fgets(str,1024,finp)!=NULL)&(fgets(str2,2,keyFile)!=NULL))
  {
    printf("%c\n %c",str2[1],str2[2]);


    /* *** START CODE THAT USES INPUT.TXT FILE & KEYS.TXT *** */
    len = strlen(str);
    for(i=0;i<len;i++)
    {
      str[i]=str[i]^str2[2];
      str[++i]=str[i]^str2[1];
      break;
    }
  }

  printf("%s\n", str);
  fclose(finp);
  return 0;

}
else
{
  printf("SORRY!");
}

Solution

  • C arrays indexes are zero based, then you should use

    str2[0],str2[1]
    

    instead of

    str2[1],str2[2]
    

    In this fragment

    for(i=0;i<len;i++)
    {
      str[i]=str[i]^str2[2];
      str[++i]=str[i]^str2[1];
      break;
    }
    

    break statement stop loop after first iteration. You should remove it. Then you get

    for(i=0;i<len;i++)
    {
      str[i]^=str2[1];
      str[++i]^=str2[0];
    }
    

    In line

    while((fgets(str,1024,finp)!=NULL)&(fgets(str2,2,keyFile)!=NULL))
    

    you need logical AND instead of bitwise

    while((fgets(str,1024,finp)!=NULL)&&(fgets(str2,2,keyFile)!=NULL))
    

    And if your input.txt file contain more the 1024 byte to show all results you need to move printf("%s\n", str); into the while loop

    while((fgets(str,1024,finp)!=NULL)&&(fgets(str2,2,keyFile)!=NULL))
    {
        ...
        printf("%s\n", str);
    }