Question

I need a sample code that show me how to hash a string with salt using openssl library. I should mention that I know how to do this without salt, as you can see in this code:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

and my question is about adding salt to the hash function, something like this, but using openssl library:

char salt[2];  /* Salt for the crypt() function  */
const char *salt_chars = "abcdefghijklmnopqrstuvwxyz" /* Range of character supported   */
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  /* as a value for salt in crypt() */
                         "0123456789";
char password1[BUFSIZ], *buf;

/* Build salt */
srand(time(NULL));
salt[0] = salt_chars[rand() % 62];
salt[1] = salt_chars[rand() % 62];

buf = crypt(password, salt);

Thanks

Was it helpful?

Solution

Salting is just concatenating salt to data in before applying hash function. Salt should be random and never twice the same, goal is to defeat precomputed rainbow tables. Salt should be stored together with the hash when checking of data ( password ) is done.

Based on your code, concanating salt in front of data is (untested whatsoever) :

bool simpleSHA256(void * salt, unsigned long salt_length, void* input, unsigned long length, unsigned char* md) 
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    // first apply salt
    if(!SHA256_Update(&context, (unsigned char*)salt, salt_length))
        return false;

    // continue with data...
    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top