tags:

views:

104

answers:

3

hello all. i'm having a problem while encrypting some data in the file. i'm using simple xor for that. lets say i have this struct:

struct MyFile{
char fileName[128];
int account;
float balance;};

saving this as a binary file is working properly but when i use xor to encrypt the filename in the struct and save the struct to hd then reading the struct and decrypting the filename is not showing the characters correctly. i'm using this simple function for the encryption/decryption purpose.

static void Codec(const char *key,int keySize,char* in,char *result,int length)  
{
    for(int i=0;i<length;i++)
        result[i]=in[i]^key[i%keySize];
}

Note that when i encrypt the filename and directly decrypt it in memory the result is right. what am i missing like why is it being changed when saved on the hard disk. please reply asap and tnx in advance...

+2  A: 

First, determine whether the data is actually being altered when it is written to the disk. Have your program print out the string in these four places:

  1. Before encrypting it
  2. After encrypting it but before writing it to the disk
  3. After reading it from the disk but before decrypting it
  4. After decrypting it

Are the results from #2 and #3 the same? If so, then the file is not being changed during the transfer to disk and back.

If #2 and #3 are different, try writing the unencrypted string to disk and reading it back out. Does this work successfully?

Write only a single such structure to a file and examine the contents of the file in a hex editor. What does the file look like while it is on the disk?

Post your write-to-disk and read-from-disk code as well, part of the problem may lie there.

bta
+2  A: 

You must open the file in binary mode. If you use C I/O (like I normally do) this means

FILE *input_file = fopen(input_file_name, "rb");
FILE *output_file = fopen(output_file_name, "wb");

If instead you've been tricked into using C++ streams this means

std::ifstream input_file(input_file_name, ios::in | ios::binary);
std::ofstream output_file(output_file_name, ios::out | ios::binary);
6502
+1  A: 

Note that you need to open the files in binary mode ("rb"/"wb" instead of "r"/"w" for fopen). Windows C implementations in particular have problems regarding \n<->\r\n conversion.

It is also a good idea to use unsigned chars for arithmetic and bitwise operations; anything but 8-bit two's complement signed chars might cause trouble (which, granted, most implementations use and might not cause any trouble with symmetric XOR encryption, but it's still good to be careful.)

aib