在c编程中使用openssl进行盐的MD5 / SHA1哈希

时间:2013-12-22 11:57:20

标签: c hash openssl salt

我需要一个示例代码,向我展示如何使用openssl库使用salt散列字符串。 我应该提一下,我知道如何在没有盐的情况下做到这一点,正如您在此代码中所看到的那样:

#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;
}

我的问题是关于向hash函数添加salt,就像这样,但是使用openssl库:

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);

由于

1 个答案:

答案 0 :(得分:1)

Salting只是在应用哈希函数之前将salt与数据连接起来。 盐应该是随机的,永远不会是两倍相同,目标是击败预先计算的彩虹表。在检查数据(密码)时,Salt应与哈希一起存储。

根据您的代码,在数据前面添加盐是(未经测试):

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; 
}
相关问题