mardi 27 mars 2018

Decrypt an tex file encrypted with rand()

Question I'm trying to solve

The approach I want to take is to bruteforce all possible keys (seeds) until I find the right one. I know the first characters in the tex file so these are what I'm testing against. When I find the right sequence, I would stop the program and output the key.

/* The ISO/IEC 9899:1990 edition of the C standard */

#include <stdio.h>
#include <time.h>
#include <iostream>

//#define RAND_MAX 32767
static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
    next = seed;
}

using namespace std;

//Return a byte at a time of the rand() keystream
 char randchar() { 
  static int key;
  static int i = 0;

  i = i % 4;
  if (i == 0) key = rand();
  return ((char *)(&key))[i++];
}

int main(int argc, const char* argv[]) {


  for (unsigned int i = time(NULL); i >= 0; i--) //Try all possible return values of time(NULL) since today
  {

      srand(i); 

      cout << "Trying with time(NULL) = " << i << endl;

      FILE *input, *output;
      input = fopen("Homework1b-Windows.tex.enc", "r");
      output = fopen("Homework1b.tex", "w");

      int c,rc, test;
      int pos;
      pos = 0;
      bool pos0, pos1, pos2, pos3, pos4, pos5;
      pos0 = pos1 = pos2 = pos3 = pos4 = pos5 = false;
      char temp1, temp2;

      while ((c = fgetc(input)) != EOF) {
        rc=randchar();
        fputc(c^rc,output);

        test = c^rc;

        temp1 = (char)test;


        temp2 = '\\';

        if ((pos == 0) && (temp1 == temp2))
        {
                 pos0 = true;
        } 

        temp2 = 'd';

        if ((pos == 1) && (temp1 == temp2))
        {
                 pos1 = true;
        }

        /*

        temp2 = 'o';

        if ((pos == 2) && (temp1 == temp2))
        {
                 pos2 = true;
        }

        temp2 = 'c';

        if ((pos == 3) && (temp1 == temp2))
        {
                 pos3 = true;
        }

        */

        temp2 = 'u';

        if ((pos == 4) && (temp1 == temp2))
        {
                 pos4 = true;
        }

        temp2 = 'm';
        if ((pos == 5) && (temp1 == temp2))
        {
                 pos5 = true;
        }

        pos++;

      }
      fclose(input);
      fclose(output);

      if (pos0 && pos1 && pos4 && pos5)
      {
         cout << endl << "Cracked. The seed is time(NULL) = " << i << endl;
         break;
      }
  }

  system("pause");


}

I know that the decrypted tex file starts with "\document".

The problem I'm facing is that the code never terminates. It never finds the right key (seed).

Any help?

Thank you.




Aucun commentaire:

Enregistrer un commentaire