Search code examples
c++keysalt-cryptographypassword-hash

Accepted Method to Generate Salt for a password-hash function - C++


I am in the process of programming a password manager(for educational purposes only!) in C++. To generate the master key, my program will run the previously inputed master password through the password hashing function argon2 to generate a master key. I have 1 problem. I need a way to generate salt for use with that hash function. From my previous research(Google search: "generate salt c++", and searching StackOverflow), I have seen people do various things similar to this:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";

int stringLength = sizeof(alphanum) - 1;

char genRandom()  // Random string generator function.
{

    return alphanum[rand() % stringLength];
}

int main()
{
    srand(time(0));
    for(int z=0; z < 21; z++)
    {
        cout << genRandom();

    }
    return 0;

}

My question is: Will generating a random string with rand() be enough, or is there a more accepted method of generating salt, or a library that can do it for me?

P.S When I searched StackOverflow, I could really only find articles on PHP and C#.


Solution

  • If you really just need a salt, i.e., something you can hash with a password to make the hash unique, then it just needs to be unique. In particular it doesn't need to be random or unguessable in any way.

    I would concatenate the real time system clock with a counter.

    Using the system clock guarantees that values will be unique for different runs of my program, and using the counter guarantees that values will be unique within the same run of my program.

    This is appropriate for server-type scenarios where the same process handles lots of passwords. If your program might run many times per second, or have many instances running in parallel, add the process ID too. If your process is distributed, include the server IP address or MAC.

    It's also fine to call whatever version of uuidgen() your system has, OR to use a real cryptographic random number generator.

    Note that lot of implementations use really short salts, even though keeping the salt short is completely unnecessary. Don't do that, because it makes it hard to make sure they're unique.