Reverse engineering code

Hi there, I am currently doing an assignment where I have to write a code to decrypt a text file that is given to me. I am just stuck on how to reverse engineer the encrypting code, which is as follow:

char decode(char aChar)
{
int result = 1 + (rand() % 127);
result = aChar - result;

if (result < 0)
{
result = result - 128;
}
return result;
}

My code works but when I run the program it encrypts the already encrypted text file. Any help would be much appreciated.
Last edited on
important: first srand again for the same seed as was used to encrypt. that is, if the encrypt calls srand(0) then the decrypt needs to call srand(0).

then just reverse the math.

question one...
how do you know that result was result - 128 from the answer, vs not having this operation? If you can't tell from the data, its not reversible. It is very easy to write things you can't undo. Did you make this up yourself?
Last edited on
Thanks for the help, as for your question, I was already given that code and was asked to reverse it.
ok. you need to figure out how to undo that last if-statement's work. The rest looks simple.
Adam, are you sure that's result = result -128 and not result = result + 128? Addition would make a whole lot more sense in this context.
apologies the pseudo-code they gave us was:

The decode function implements the reversal of the Caesar encoding
let Result := 1 + rand() modulo 127;
Result := CharToDecode – Result;
if Result < 0 then
Result := Result + 128;
return Result;

yet I am still having trouble reversing the math in this one. We know that the offset is going to be 92, and that there are 128 characters in the ASCII table. We have been given the equation of encoding the Cipher as ‘A’ + ((aChar – ‘A’ + aOffset) % 26).
So i tried working out the math but the output is till incorrect, this is my code:

char decode(char aChar)
{
int result = 1 + (rand() % 127);
int CharToDecode = aChar;
if (CharToDecode > (128 - result ))
{
CharToDecode = CharToDecode - 128 + 4;
}
CharToDecode = CharToDecode + result;
return CharToDecode;
}

I can't see what is wrong with the code as I did a sample file and it worked giving me the correct output.
did you reset rand() with a srand() call as I said?

I had the srand() inside a while loop therefore it was giving me random numbers. All I had to do is follow the pseudo code that was given to me but it didn't specify where the srand() should go, therefore creating this confusion.
Topic archived. No new replies allowed.