如何创建用户密码哈希

时间:2014-08-14 17:02:35

标签: c++ passwords crypto++ pbkdf2

我们正在将代码转换为使用Crypto ++库。要为我们的用户创建哈希密码,这一切都是必要的吗?只是想确保我们不会错过一些重要的部分。 谢谢你

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

1 个答案:

答案 0 :(得分:0)

一些评论......

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

AES的用途是什么?也许:

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

如果您想继续使用AES,CMAC可以正常工作。


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

您不应使用匿名声明。这会给某些GCC版本带来麻烦。也就是说,将您的StringSource命名为

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