XOR Encryption

Dave Sinkula 0 Tallied Votes 332 Views Share

This snippet is an example of using XOR encryption to encrypt/decrypt a file. It uses command-line input parameters as follows:argv[1] - name of input file to encrypt/decrypt
argv[2] - name of output file
argv[3] - crypt keyFor example, an input file called "main.c" is used to create an output file "file.bin" with the encryption key "key" by doing this:

H:\Daniweb>xorcrypt main.c file.bin key

Performing the reverse on the encrypted file "file.bin" will restore the original file contents into another output file "file.txt" using the same "key".

H:\Daniweb>xorcrypt file.bin file.txt key

If the code shown here was in "main.c", you should find that the second output "file.txt" matches "main.c".

#include <stdio.h>

int main(int argc, char *const *argv)
{
   if ( argc == 4 )
   {
      FILE *input  = fopen(argv[1], "rb");
      FILE *output = fopen(argv[2], "wb");
      if ( input != NULL && output != NULL )
      {
         unsigned char buffer[BUFSIZ];
         size_t count, i, j = 0;
         do {
            count = fread(buffer, sizeof *buffer, sizeof buffer, input);
            for ( i = 0; i < count; ++i )
            {
               buffer[i] ^= argv[3][j++];
               if ( argv[3][j] == '\0' )
               {
                  j = 0; /* restart at the beginning of the key */
               }
            }
            fwrite(buffer, sizeof *buffer, count, output);
         } while ( count == sizeof buffer );
         fclose(input);
         fclose(output);
      }
   }
   return 0;
}
vonqi 0 Newbie Poster

Hi

i aM new here . Like to know where can i get xorcrypt <-- this program. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.