Search code examples
c++passwordscrypto++pbkdf2

How to create user password hash


We are in the process of converting code to use Crypto++ library. To create a hashed password for our users is this all that is necessary? Just want to make sure we aren't missing some important piece. Thanks you

void test_create_hash(void)
{
   using namespace CryptoPP;
   std::string password = "this is a users password";
   unsigned int iterations = 1000000;

   AutoSeededRandomPool rng;

   SecByteBlock pwsalt(AES::DEFAULT_KEYLENGTH);
   rng.GenerateBlock(pwsalt,pwsalt.size());

   SecByteBlock derivedkey(AES::DEFAULT_KEYLENGTH);

   PKCS5_PBKDF2_HMAC<SHA256> pbkdf;

   pbkdf.DeriveKey(
      derivedkey, derivedkey.size(),
      0x00,
      (byte *) password.data(), password.size(),
      pwsalt, pwsalt.size(),
      iterations
   );
   std::string salthex;
   StringSource ss1(pwsalt,pwsalt.size(),true,
          new HexEncoder(
             new StringSink(salthex)
          )
        );
   std::string derivedhex;
   StringSource ss2(derivedkey,derivedkey.size(),true,
          new HexEncoder(
             new StringSink(derivedhex)
          )
        );

   cout << "salt stored to database:" << salthex << std::endl;
   cout << "password stored to database:" << derivedhex << std::endl;
}

Solution

  • A few comments...

    SecByteBlock pwsalt(AES::DEFAULT_KEYLENGTH);
    SecByteBlock derivedkey(AES::DEFAULT_KEYLENGTH);
    

    What's up with AES? Perhaps:

    SecByteBlock pwsalt(SHA256::DIGEST_SIZE);
    SecByteBlock derivedkey(SHA256::DIGEST_SIZE);
    

    A CMAC works fine if you want to keep using AES.


    std::string salthex;
    StringSource ss(pwsalt,pwsalt.size(),true,
        new HexEncoder(
            new StringSink(salthex)
        )
    );
    

    You should not use anonymous declarations. It causes trouble for some GCC versions. That is, name your StringSource.

    std::string salthex;
    StringSource ss(pwsalt,pwsalt.size(),true,
        new HexEncoder(
            new StringSink(salthex)
        )
    );