声明相同类型的变量并重用它们

时间:2015-10-20 16:54:45

标签: c++ crypto++

我有以下情况,并想知道是否有一个很好的解决方案。

我正在使用Crypto++并声明以下内容:

if (_HashType == SHA1)
{
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA1> pbkdf;
    pbkdf.DeriveKey(...)
}
else if (_HashType == SHA256)
{
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA256> pbkdf;
    pbkdf.DeriveKey(...)
}
else if (_HashType == SHA384)
{
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA384> pbkdf;
    pbkdf.DeriveKey(...)
}
else if (_HashType == SHA512)
{
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA512> pbkdf;
    pbkdf.DeriveKey(...)
}

我想做的是这样的事情:

PKCS5_PBKDF2_HMAC<?> pbkdf;     
if (_HashType == SHA1)
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA1> pbkdf;
else if (_HashType == SHA256)
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA256> pbkdf;
else if (_HashType == SHA384)
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA384> pbkdf;
else if (_HashType == SHA512)
    PKCS5_PBKDF2_HMAC<CryptoPP::SHA512> pbkdf;

pbkdf.DeriveKey(...)    

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

PKCS5_PBKDF2_HMAC<>的公共基类是PasswordBasedKeyDerivationFunction,所以你可以做的是:

PasswordBasedKeyDerivationFunction* pbkdf;     
if (_HashType == SHA1)
    pbkdf = new PKCS5_PBKDF2_HMAC<CryptoPP::SHA1>();
else if (_HashType == SHA256)
    pbkdf = new PKCS5_PBKDF2_HMAC<CryptoPP::SHA256>();
else if (_HashType == SHA384)
    pbkdf = new PKCS5_PBKDF2_HMAC<CryptoPP::SHA384>();
else if (_HashType == SHA512)
    pbkdf = PKCS5_PBKDF2_HMAC<CryptoPP::SHA512>();

pbkdf->DeriveKey(...)    

//...
delete pbkdf;

如果您使用的是C ++ 11或更高版本,则可以使用智能指针,而不必担心内存管理:

std::unique_ptr<PasswordBasedKeyDerivationFunction> pbkdf;     

if (_HashType == SHA1)
    pbkdf.reset(new PKCS5_PBKDF2_HMAC<CryptoPP::SHA1>());
else if (_HashType == SHA256)
    pbkdf.reset(new PKCS5_PBKDF2_HMAC<CryptoPP::SHA256>());
else if (_HashType == SHA384)
    pbkdf.reset(new PKCS5_PBKDF2_HMAC<CryptoPP::SHA384>());
else if (_HashType == SHA512)
    pbkdf.reset(PKCS5_PBKDF2_HMAC<CryptoPP::SHA512>());

pbkdf->DeriveKey(...)