我需要一个示例代码,向我展示如何使用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;
}


我的问题是关于将盐添加到哈希函数中,类似这样,但是使用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);


谢谢

最佳答案

盐化只是在应用哈希函数之前将盐与数据串联在一起。
盐应该是随机的,并且永远不能相同,目的是击败预先计算的彩虹表。完成数据(密码)检查时,应将盐与哈希一起存储。

根据您的代码,在数据前添加盐(无论如何):

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

10-08 08:28
查看更多