/* HackDemo example 1

   Name   : demo1
   Version: v0.01
   Date   : Tuesday, 20th January 2004

   Purpose: Hacking "protection" systems, example 1

   Creator: Rick Murray
            for Frobnicate issue #20

            http://www.heyrick.co.uk/frobnicate/

            NEEDS NEWER C COMPILER UNLESS YOU'D
            CARE TO JIGGLE THE CODE SLIGHTLY...
*/




// Included files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "kernel.h"



char username[64] = "";



int  load_keyfile(void);



int  main(void)
{
   // ...program start-up code would go here...

   if (load_keyfile() != 255)
   {
      fprintf(stderr, "Invalid registration, unable to continue...\n");
      exit(EXIT_FAILURE);
   }

   // ...rest of program would come here...

   printf("Program loaded, user \"%s\"...\n", username);

   return 0;
}



int  load_keyfile(void)
{
   // Keyfile format:
   //    <byte>   Check value of all chars summed, ANDed with 255
   //    <byte>   Check value that, when added to check, makes 255
   //    <bytes>  Username, EORed with previous encoded byte

   int  check = 0;
   int  twofivefive = 0;
   int  byte = 0;
   int  oldbyte = 0;
   FILE *fp = NULL;

   // open file
   fp = fopen("<FrobTest$Dir>.keyfile", "rb");
   if (fp == NULL)
   {
      printf("Missing keyfile!\n");
      return 0;
   }

   // load data (and close file)
   check = fgetc(fp);
   twofivefive = fgetc(fp);
   for (int loop = 0; loop <= 60; loop++)
      username[loop] = fgetc(fp);
   fclose(fp);

   // do the sum check
   byte = 0; // we'll use this for the summing
   for (int loop = 0; loop <= 60; loop++)
      byte = byte + username[loop];
   if ( (byte & 0xFF) != check)
      // check failed!
      return 0;

   // decode username
   oldbyte = 48;
   for (int loop = 0; loop < 60; loop++)
   {
      byte = username[loop];
      username[loop] = byte ^ oldbyte;
      oldbyte = byte; // it works on the ENCODED version
   }

   // return with value that should be '255'
   return (check + twofivefive);
}
