简体   繁体   中英

Cut characters for a string in C

Here's some code.

#include <stdio.h>

int main()
{
    char npass[] = "$1$bUZXMjKz$08Ps4NPTfj6ZNkoqrsP/D.";
    char salt [12];
    int i;
    for (i = 0; i < 12; i++)
    {
            npass[i+3] = salt[i];
            i++;
    }
    salt[12] = '\0';
    puts(salt);
    return 0;
}

Basically, npass is an md5crypt result(password is admin). In order to verify this, I need to separate the salt from the result.

My understanding is that a string in C is really a char array containing all the letters alone(with '\\0' at the end). I use a for loop to cut the first three characters but I guess because of ASLR , the results that I get are always random ones. Actually, without ASLR , I get the same random result always.

Of course you get "random" data, you assign to the hash and not the salt. You want the other way around:

salt[i] = npass[i+3];

Or you could skip the loop and do:

memcpy(salt, npass + 3, sizeof(salt) - 1);
salt[sizeof(salt) - 1] = '\0';

With all bugs already pointed out, and some aesthetic fixes, you should end up with something like this:

#include <stdio.h>
#include <string.h>

#define SALT_N 12

int main()
{
    const char npass[] = "$1$bUZXMjKz$08Ps4NPTfj6ZNkoqrsP/D.";
    char salt [SALT_N+1];

    memcpy(salt, npass, SALT_N);
    salt[SALT_N] = '\0';
    puts(salt);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM