Thread: Encode strings in C code

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    21

    Encode strings in C code

    Hi,

    I'm trying to encode all my dll strings in my C code. So, for instance, if I have a:

    Code:
    sprintf(var1, "hello %s", name);
    I want to encode "hello %s", or create a new function that might encode this instruction given a key. And encode (and decrypt) any string like "Info 1", for example.

    Any sugestions?

    Kind regards,

    JKepler

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I don't understand what you're asking.

  3. #3
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Hi,

    Thanks for the attention. I was trying to do something like:

    Code:
    sprintf(var1, decrypt("awesrte67"), name);
    where decrypt("awesrte67") is decrypted to "hello %s".

    Is it possible?

    Kind regards,

    JKepler

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Sure, that's possible.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    // Here the simple encrypting is to add one.
    // So "hello %s" becomes "ifmmp!&t".
    // decrypt subtracts one to obtain the original string.
    char *decrypt(char *buf, const char *from) {
        char *to = buf;
        while (*from) *to++ = *from++ - 1;
        *to = '\0';
        return buf;
    }
    
    int main(void) {
        char str[100], buf[100], name[100] = "joe";
        sprintf(str, decrypt(buf, "ifmmp!&t"), name);
        printf("[%s]\n", str);
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Hi algorism,

    Your solution is simply...brilliant - and it works like a charm

    Now, I'm trying to make a XOR with the string. Supose the encrypted string has a key="12345"

    I'm trying:

    Code:
    char *decrypt2(char *buf, const char *from, char *key) {
        char *to = buf;
        while (*from) *to++ = *from++^*key++;    
        *to = '\0';
        return buf;
    }
    And calling it:

    Code:
    sprintf(str, decrypt2(buf, "[PY\]^d\GYU","12345"), name);
    But I don't get all the characters - some are scrambled...

    Can you please tell me what am I doing wrong?

    Regards,

    JKepler

  6. #6
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    You need to put two backslashes for every backslash you want in your string. And you have to wrap the key around when it gets to the end. You also probably shouldn't be using str for the "to" string of decrypt and also for the string to which sprintf is writing. What is the original string?
    Code:
    #include <stdio.h>
    
    char *crypto(char *out, const char *from, const char *key) {
        const char *k = key;
        char *to = out;
        while (*from) {
            *to++ = *from++ ^ *k++;
            if (*k == '\0') k = key;
        }
        *to = '\0';
        return out;
    }
    
    int main(void) {
        char plain[100] = "hello %s", cipher[100], key[] = "12345";
        char str[100], name[]="joe";
    
        crypto(cipher, plain, key);
        printf("[%s]\n", cipher); // not necessarily all printable characters
    
        sprintf(str, crypto(plain, cipher, key), name);
        printf("[%s]\n", str);
    
        // This prints [jbjhhoVosld]
        sprintf(str, crypto(plain, "[PY\\]^d\\GYU", key), name);
        printf("[%s]\n", str);
    
        return 0;
    }

  7. #7
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Hi,

    Once again thanks It's a great and simple solution. Just one more question if I may: if I have a string with an hexadecimal value (like "22f5e789") how can I convert it into a ascii symbols variable? I can't seem to find a straight answer in Google. Most allow the printing of that string - not saving it in a variable function.

    Sorry for the trouble.

    Kind regards,

    JKepler

  8. #8
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I think you mean something like this:
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    void tohex(char *out, const char *in) {
        for ( ; *in; in++, out += 2)
            sprintf(out, "%02x", (unsigned char)*in);
        *out = '\0';
    }
    
    void fromhex(char *out, const char *in) {
        unsigned n = 0;
        for (int pos = 0; sscanf(in, "%2x%n", &n, &pos) == 1; in += pos)
            *out++ = (char)n;
        *out = '\0';
    }
    
    void dump(char *res) {
        for (unsigned char *r = (unsigned char*)res; *r; r++)
            printf("%02x %3u %c\n", *r, *r, isprint(*r) ? *r : '.');
    }
    
    int main(void) {
        const char str[] = "22f5e789414243303132";
        char res[100];
    
        printf("[%s]\n", str);
        fromhex(res, str);
        dump(res);
    
        const char s[] = "hello WORLD!!";
        char t[100];
        tohex(t, s);
        printf("[%s]\n", t);
        
        fromhex(res, t);
        dump(res);
    
        return 0;
    }

  9. #9
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Good morning algorism,

    Works like a charm. Thanks for the help - and I've learned a lot, believe me. You are a good teacher.

    Kind regards,

    JKepler

  10. #10
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Good evening algorism,

    I've realized something (my code is working well though): it's not possible to use the encryption to the values of an array, is it?

    I mean, if an array is like
    Code:
    {"hello", "hi",...}
    I can't make it like
    Code:
    {crypto(plain,"ghdgte",name),...
    for example, can I? The function will not be assumed as variable I think...

    Must I create a set of variables like
    Code:
    a=crypto(plain,"ghdgte",name),...
    and then apply to the array
    Code:
    {a,...
    ?

    Your advice is highly regarded.

    Kind regards,

    JKepler

  11. #11
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Maybe this will do.
    Code:
    #define MAXSTRINGS 10
    #define MAXSTRSIZE 50  // long enough to hold longest string (and terminating null char)
    char str[MAXSTRINGS][MAXSTRSIZE];
    crypto(str[0], "ghdgte", name);
    crypto(str[1], "xywzyd", name);
    //...
    If it's better to dynamically allocate the space for each string then something like this:
    Code:
    char *str[MAXSTRINGS];
    char buf[MAXSTRSIZE];
    str[0] = strdup(crypto(buf, "ghdgte", name));
    str[1] = strdup(crypto(buf, "xywzyd", name));
    //...
    You might want to free that memory at some point. If it's used throughout the run of the program then you can just let the OS clean up.

  12. #12
    Registered User
    Join Date
    Aug 2015
    Posts
    21
    Hi algorism,

    I'm sorry for the late reply, but I had to go for one day to Lisbon... I've tryed both codes, and the compiler doesn't let me cast a function value in a constant. I've tryed this in the .c file. Must it be in the header? I would like to apply the encrypt to #define string values and constant string values and structures.

    This is actually a commom problem in Google.

    Hope to hear from you soon.

    Kind regards,

    JKepler

  13. #13
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    It's difficult to understand exactly what you need. A stripped-down example would be useful.

    You won't be able to decrypt string constants in place. You need a string variable with enough space to decrypt to.
    Code:
    #define GREETING_ENC "YW_XZ\x11""F[QGT"
    char GREETING[sizeof GREETING_ENC];
    
    int main(void) {
        const char *key = "12345";
        crypto(GREETING, GREETING_ENC, key);
    
        printf("%s\n", GREETING);
    
        return 0;
    }
    Here's a program to convert plain strings to encrypted C string constants.
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    char *crypto(char *out, const char *from, const char *key) {
        const char *k = key;
        char *to = out;
        while (*from) {
            *to++ = *from++ ^ *k++;
            if (*k == '\0') k = key;
        }
        *to = '\0';
        return out;
    }
    
    void output(const char *s) {
        printf("\"");
        for ( ; *s; s++) {
    
            // Escape double-quote and backslash.
            if (*s == '"' || *s == '\\')
                putchar('\\');
    
            // If *s is a printable character, print as is.
            if (isprint(*s))
                printf("%c", *s);
    
            // Otherwise convert to two-digit hex value.
            else
                // After the two-digit hex value, two double-quotes
                // are output to separate it from further hex digits
                // (unless it's the last character)
                printf("\\x%02x%s", (unsigned char)*s,
                    !*(s+1) ? "" : "\"\"");
        }
        printf("\",\n");
    }
    
    int main(void) {
        const char *plain[] = {
            "hello there",
            "another string",
            "more stuff",
            NULL
        };
        char cipher[200], *key = "12345";
        for (const char **p = plain; *p; p++) {
            crypto(cipher, *p, key);
            output(cipher);
        }
        return 0;
    }
    Last edited by algorism; 09-21-2016 at 12:24 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Base54 Encode/Decode
    By MartinR in forum C Programming
    Replies: 2
    Last Post: 01-25-2014, 06:08 AM
  2. how to encode Chinese characters?
    By gholamghar in forum C++ Programming
    Replies: 1
    Last Post: 04-03-2010, 11:20 AM
  3. XML Encode Help.
    By userpingz in forum C# Programming
    Replies: 2
    Last Post: 11-12-2009, 08:06 PM
  4. frustration on URL encode-decode
    By Lince in forum C Programming
    Replies: 22
    Last Post: 08-22-2007, 05:36 PM
  5. encode voice to mp3
    By nihong98 in forum Linux Programming
    Replies: 2
    Last Post: 07-27-2002, 06:13 AM

Tags for this Thread