【问题标题】:MD5/ SHA1 hash with salt using openssl in c programming在 c 编程中使用 openssl 带盐的 MD5/SHA1 哈希
【发布时间】:2013-12-22 11:57:20
【问题描述】:

我需要一个示例代码,向我展示如何使用 openssl 库用盐对字符串进行哈希处理。 我应该提一下,我知道如何在不加盐的情况下做到这一点,正如您在这段代码中看到的那样:

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

谢谢

【问题讨论】:

  • 看看 openssl 测试代码( git clone ... 然后 cd test )。看看wiki.openssl.org。然后知道加盐数据意味着在 salt.data 上应用哈希,其中 .是连接,创建自己的盐应该不难。 HMAC 等其他一些键控功能也被大量用于保护密码,例如 PBKDF2 (security.stackexchange.com/questions/29951/…)。

标签: c hash openssl salt


【解决方案1】:

加盐只是在应用哈希函数之前将盐与数据连接起来。 盐应该是随机的,并且永远不会重复,目标是击败预先计算的彩虹表。完成数据(密码)检查时,盐应该与哈希一起存储。

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

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

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2012-04-15
    • 2012-03-06
    • 2011-08-16
    相关资源
    最近更新 更多