XOR.c — XOR Encryption Demo C Program

Download xor.c

//* XOR encryption filter program
   Written 9/2006 by Wayne Pollock, Tampa Florida USA.
   $Id: xor.c,v 1.0 2006/09/08 18:17:47 wpollock Exp $
*/

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

static const int MAX_PASSWORD_LENGTH = 32;

int main ( int argc, char *argv[] )
{
    FILE * console;
    char password[MAX_PASSWORD_LENGTH];
    char byte = 0;
    int i = 0;

    /* Read in password: */

    console = fopen( "/dev/tty", "r" );
    fprintf( stderr, "Enter Password: " );
    fgets( password, MAX_PASSWORD_LENGTH, console );
    fclose( console );
    password[strlen(password)-1] = '\0';  /* remove newline */

    /* XOR each byte of stdin with a byte of the password,
       reusing the password when we reach the end: */

    while ( fread( &byte, 1, 1, stdin ) == 1 )
    {
        byte = byte ^ password[i];
        fwrite( &byte, 1, 1, stdout );

        ++i;
        if ( i >= strlen(password) )   i = 0;
    }
    
    return 0;
}