简体   繁体   English

在C编程中使用openssl在MD5 / SHA1哈希上加盐

[英]MD5/ SHA1 hash with salt using openssl in c programming

I need a sample code that show me how to hash a string with salt using openssl library. 我需要一个示例代码,向我展示如何使用openssl库使用salt对字符串进行哈希处理。 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: 我的问题是关于将盐添加到哈希函数中,类似这样,但是使用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);

Thanks 谢谢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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