Thread: Encrypting and knowing if it's encrypted

  1. #1
    C <3er
    Join Date
    Jul 2011
    Posts
    46

    Unhappy Encrypting and knowing if it's encrypted

    Hello there!
    Well i'll present my problem: As a part of a bigger program I was trying to encrypt a file using basic xor encrypting, I can encrypt and decrypt files easily. The problem is in my "bigger" program I would like to open the file and read its data but what if its encrypted? well I went over this thinking about using a magic key at the start of the encrypted file for example "EN\n" then if I read the first line and the program found the magic key it would know that the file is encrypted, decrypt it and read the data. Problem comes when trying to decrypt and depending on the key even trying to encrypt since sometimes I experienced that \n wasn't being printed to the file... Here's a sortened version of a small encrypt program I made to test the problem...

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXLEN 256
    
    #define MAGICKEY "EN"
    
    void encrypt_file(FILE *src, FILE *dest, char *key);
    void copy_file(FILE *src, FILE *dest);
    
    int main()
    {
        FILE *f, *tmp, *tmp2;
        char s[MAXLEN], key[MAXLEN], magic[MAXLEN];
    
        printf("Enter file name: ");
        fflush(stdin);
        gets(s);
    
        f = fopen(s, "r");
        if(f == NULL){
            printf("ERROR: Couldn't open file %s\n", s);
            return -1;
        }
        tmp = fopen("tmp.txt", "w");
        if(tmp == NULL){
            printf("ERROR: Couldn't write temp file\n");
            return -1;
        }
    
        printf("Enter key: ");
        fflush(stdin);
        gets(key);
    
        fscanf(f, "%s", magic);
        if(strcmp(magic, MAGICKEY) == 0){
            fgetc(f); // get rid of '\n'
            copy_file(f, tmp);
    
            tmp2 = fopen("tmp2.txt", "w");
            if(tmp2 == NULL){
                printf("ERROR: Couldn't write temp file\n");
                return -1;
            }
    
            encrypt_file(tmp, tmp2, key);
            fclose(tmp2);*/
            fclose(tmp);
            fclose(f);
    
            remove(s);
            remove("tmp.txt");
            rename("tmp2.txt", s);
    
        }else{
            rewind(f);
            encrypt_file(f, tmp, key);
            rewind(tmp);
            fprintf(tmp, "%s\n", MAGICKEY);
    
            fclose(tmp);
            fclose(f);
    
            remove(s);
            rename("tmp.txt", s);
        }
    
        return 0;
    }
    
    void encrypt_file(FILE *src, FILE *dest, char *key){
        int i, b;
    
        i = 0;
        while((b = fgetc(src)) != EOF){
            fputc(b ^ key[i], dest);
    
            ++i;
            if(i == strlen(key))
                i = 0;
        }
    }
    
    void copy_file(FILE *src, FILE *dest){
        int c;
        while((c = fgetc(src)) != EOF)
            putc(c, dest);
    }
    I tried binary reading mode but doesn't seem to work cause I have to remove the \n and since this varies from OS to OS as I understood, I'm having a headache and don't know how to go about it...
    Thanks in advance!

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Are you sure you want to encrypt the "magic key"?

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Programs like bcrypt change the extension of the encrypted file (IE foo.doc becomes foo.doc.bfe). Then when the program is fed a file ending with the new extension it can treat this as a decrypt operation.

    Your magic key idea would also work. Some image and executable file formats will use a byte sequence at the start of a file to signify how its used. Better to set this to a certain length instead of trying to read a string with fscanf as you are

  4. #4
    C <3er
    Join Date
    Jul 2011
    Posts
    46
    @CommonTater No I don't want to encrypt the magic key, magic key is added after encryption is done, as you can see in my code,
    @Fordy About the extension changing it's a great idea the problem is files are read with txt extension always I mean the option is like Open File and I don't distingish between Open File and Open Encrypted File, so maybe the length of the key is a good idea, thanks
    Anyways, I think I should open the file as binary because some characters can get encrypted as EOF as I read while searching, in other post. But... any other solutions to my problem?
    Thanks in advance! And thanks again both of you :P

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    How big are these files?

    On modern systems it should be no problem to load an entire file into memory and work on it there. This would allow you to simply open the file in binary mode, use malloc() to create a file sized buffer, use fread() to load the whole thing in one pass then close the file. Now you have it in a place where you can manipulate it any way you like.

    Code:
    int fs = 0;             // file size
    FILE *lf = NULL;        // file handle
    unsigned char *fm;      // file in memory
    
    //open file
    lf = fopen(FileName,"rb");
    if (!lf)
      { printf("Well that certainly didn't work!");
         exit(1); }
    
    // get file size
    fseek(lf, 0, SEEK_END);
    fs = ftell(lf);
    fseek(lf, 0, SEEK_SET);
    
    // create memory block (always take a few extra bytes)
    fm = malloc(fs + 10);  
    if (!fm)
      { printf("Crap, that didn't work either");
         fclose(lf);
         exit (1); }
    
    // now we load the file
    if ( fread (fm,fs,1,lf) != fs)
      {printf ("Gees, the file didn't load");
        fclose(lf);
        exit (1); }
    fclose(lf); 
    
    // process the file here....
    I'm suggesting this because adding the magic key to the file after it's written is going to either a) overwrite the first few characters of the file or b) add to the end of the file... either may interfere in the decryption process. If you read the whole thing into memory work on it there then write it all back out in one big blob there's far less chance of "polluting" the disk file.
    Last edited by CommonTater; 07-28-2011 at 09:22 AM.

  6. #6
    C <3er
    Join Date
    Jul 2011
    Posts
    46
    Thanks commontater that seems very interesting and makes sense
    Anyways I didn't experience any overwriting (at least non that one can see), my question now is when you say process the file here you mean processing it character by character like shifting all the characters for example two places and then adding magic key 'EN' and then writing it to file?
    Thanks in advance!

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by beta3designs View Post
    Thanks commontater that seems very interesting and makes sense
    Anyways I didn't experience any overwriting (at least non that one can see), my question now is when you say process the file here you mean processing it character by character like shifting all the characters for example two places and then adding magic key 'EN' and then writing it to file?
    Thanks in advance!
    In the interests of efficiency I would do a little check.

    If you've loaded an encrypted file the magic key should already be there so you can test for it. If it is there take a starting point 2 bytes over and decrypt the file... If not the file is not encrypted so you don't take an offset... the resulting data can be passed to your application as a memory pointer.

    If you are writing encrypted data... write the magic key to disk (this will advance the file pointer for you) encrypt the memory data and write it out as one big blob. If you are writing a non encrypted output... just write the data.

  8. #8
    C <3er
    Join Date
    Jul 2011
    Posts
    46
    Alright thanks I was also using that kind of check in my first code so I was aware of doing that but I was struggling with the last part you wrote so yeah writing the magic key to file and then adding the encrypted blob to it makes much more sense than trying to encrypt the blob then adding the magic key to it then writing to file... Thank you very much I wasn't at home but the problem should be gone so I'll mark this as solved! Thanks again! EDIT: One last question, if I test for the magic key, should I take that starting point to bytes over? I mean if I'm reading to test for the magic key the pointer should be positioned correctly shouldn't it? I think I should rewind or fseek to SEEK_SET when the magic key is not there am I right? Thanks

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    I wouldn't test for the magic key in the disk file... I'd just snap it up and get it into memory...then test it.

    Following on my previous example...

    Code:
     
    int TestKey(char *buff, char *key)
      { return strncmp(buff, key, strlen(key) ); }
    That will return zero if the key is present, non-zero otherwise.


    Then...
    Code:
    unsigned char *TxtPtr = NULL;  // pointer to start of text 
    
    if (! TestKey(fm,key))  // or whatever your magic key is.
      { TxtPtr = fm + strlen(key);
         decrypt(TxtPtr); }
    else
      { TxtPtr = fm; }
    
    // hand the text at TxtPtr over to your app here.
    Don't disturb the actual memory pointer (fm in the examples) or free() will fail when you dismiss it.
    Last edited by CommonTater; 07-28-2011 at 02:41 PM.

  10. #10
    C <3er
    Join Date
    Jul 2011
    Posts
    46
    Ok thank you very much! ^^
    EDIT: BTW, in your code
    Code:
    fread (fm,fs,1,lf)
    should be;
    Code:
    fread (fm,1,fs,lf)
    Last edited by beta3designs; 07-28-2011 at 05:06 PM.

  11. #11
    Registered User kryptkat's Avatar
    Join Date
    Dec 2002
    Posts
    638
    what if the "blob" of data starts with "EN" the same as magickey ? a small possibility but a possibility none the less. meow. think you need a better system.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by kryptkat View Post
    what if the "blob" of data starts with "EN" the same as magickey ? a small possibility but a possibility none the less. meow. think you need a better system.
    Good point... but I'm sure the "EN" was just an example.

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by beta3designs View Post
    Ok thank you very much! ^^
    EDIT: BTW, in your code
    Code:
    fread (fm,fs,1,lf)
    should be;
    Code:
    fread (fm,1,fs,lf)
    Sorry about that...

  14. #14
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by kryptkat View Post
    what if the "blob" of data starts with "EN" the same as magickey ? a small possibility but a possibility none the less. meow. think you need a better system.
    Regardless of what 'key' you use, this is always a possibility. This is where the user is expected to use the program on the right files. I could have a "blob" of data, I'll say the andyFileFormat, that begins with the same signature JPGs use to indentify them. If the user decided to open it in a picture viewer and complained because they saw garbage, I would just inform them to throw their computer away because they were clearly not smart enough to use it.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by AndrewHunter View Post
    Regardless of what 'key' you use, this is always a possibility. This is where the user is expected to use the program on the right files. I could have a "blob" of data, I'll say the andyFileFormat, that begins with the same signature JPGs use to indentify them. If the user decided to open it in a picture viewer and complained because they saw garbage, I would just inform them to throw their computer away because they were clearly not smart enough to use it.
    His key could just as easily be a DWORD or QWORD value.... nothing says it has to be ascii.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Encrypted XML
    By darren78 in forum C# Programming
    Replies: 9
    Last Post: 09-03-2010, 11:44 AM
  2. an encrypted program
    By makonikor in forum C Programming
    Replies: 13
    Last Post: 07-14-2010, 01:35 PM
  3. Writing encrypted value to file.
    By mkthnx001 in forum C++ Programming
    Replies: 13
    Last Post: 05-25-2009, 12:42 PM
  4. Reading encrypted data from file
    By cctoombs in forum C Programming
    Replies: 2
    Last Post: 02-13-2005, 02:59 AM
  5. help with encrypting plz
    By wimpman in forum C Programming
    Replies: 9
    Last Post: 03-31-2004, 03:29 PM

Tags for this Thread