Skip to content

PKCS5_PBKDF2_HMAC

Header: #include <cryptopp/pwdbased.h> | Namespace: CryptoPP Since: Crypto++ 5.0 Thread Safety: DeriveKey() is const and keeps all state local to the call

PKCS5_PBKDF2_HMAC implements PBKDF2 from PKCS #5, specified in RFC 8018, an Informational RFC that obsoletes RFC 2898. It derives keys from passwords by applying HMAC repeatedly, with an iteration count that sets the cost of each guess.

For new applications, use Argon2 instead. RFC 7914 explains that with iteration-based functions such as PBKDF2, the cost of a brute-force attack implemented in hardware drops each year even when the iteration count keeps the defender’s time constant, and that memory-hard scrypt aims to reduce that advantage. OWASP recommends Argon2id first and prefers PBKDF2 where FIPS-140 compliance is required; NIST SP 800-132 approves PBKDF2 with HMAC and an approved hash function.

Quick Example

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <string>

int main() {
    using namespace CryptoPP;

    std::string password = "user_password";

    // Generate random salt
    AutoSeededRandomPool rng;
    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    // Derive 32-byte key
    byte derivedKey[32];
    unsigned int iterations = 600000;  // OWASP figure for PBKDF2-HMAC-SHA256

    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
    pbkdf2.DeriveKey(derivedKey, sizeof(derivedKey),
                     0,  // purpose byte (unused, set to 0)
                     (const byte*)password.data(), password.size(),
                     salt, sizeof(salt),
                     iterations);
    return 0;
}

Usage Guidelines

  • Use at least 600,000 iterations with HMAC-SHA-256, the OWASP figure
  • Use a random salt of at least 16 bytes per password; SP 800-132 requires the randomly generated part of the salt to be at least 128 bits
  • Store salt alongside the derived key/hash
  • Use constant-time comparison for password verification
  • Don’t use SHA-1 for new systems; OWASP lists PBKDF2-HMAC-SHA1 as legacy only
  • Don’t use a hash that is not NIST-approved where SP 800-132 applies
  • Don’t reuse salts across different passwords
  • Don’t use for new systems if Argon2 is available

Constructor

PKCS5_PBKDF2_HMAC<HashFunction>();

The hash function is specified as a template parameter:

PKCS5_PBKDF2_HMAC<SHA256> pbkdf2_sha256;
PKCS5_PBKDF2_HMAC<SHA512> pbkdf2_sha512;
PKCS5_PBKDF2_HMAC<SHA1> pbkdf2_sha1;  // Legacy only

Methods

DeriveKey

size_t DeriveKey(byte* derived, size_t derivedLen,
                 byte purpose,
                 const byte* password, size_t passwordLen,
                 const byte* salt, size_t saltLen,
                 unsigned int iterations,
                 double timeInSeconds = 0) const;

Parameters

ParameterTypeDescription
derivedbyte*Output buffer for derived key
derivedLensize_tLength of derived key (bytes)
purposebytePurpose byte (unused, set to 0)
passwordconst byte*Password bytes
passwordLensize_tPassword length
saltconst byte*Salt bytes
saltLensize_tSalt length (min 16 bytes recommended)
iterationsunsigned intMinimum number of iterations; 0 is allowed only with a positive timeInSeconds
timeInSecondsdoubleIf > 0, keep iterating until this much time has passed, never fewer than iterations

Return Value

Returns the number of iterations performed (useful when using timeInSeconds).

Exceptions

  • InvalidArgument - iterations is 0 and timeInSeconds is not positive
  • InvalidDerivedKeyLength - derivedLen is greater than 2^32-1 bytes

MaxDerivedKeyLength

size_t MaxDerivedKeyLength() const;

Returns 2^32-1 bytes. RFC 8018 allows up to (2^32-1) * hLen bytes; the library caps the length at 2^32-1 to avoid overflow.

Complete Examples

Example 1: Password Hashing for Storage

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/secblock.h>
#include <cryptopp/osrng.h>
#include <cryptopp/misc.h>
#include <iostream>
#include <string>

using namespace CryptoPP;

// OWASP figure for PBKDF2-HMAC-SHA256
const unsigned int ITERATIONS = 600000;

struct PasswordHash {
    SecByteBlock salt;
    SecByteBlock hash;
};

SecByteBlock deriveHash(const std::string& password, const SecByteBlock& salt) {
    SecByteBlock hash(32);
    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
    pbkdf2.DeriveKey(hash, hash.size(),
                     0,
                     (const byte*)password.data(), password.size(),
                     salt, salt.size(),
                     ITERATIONS);
    return hash;
}

// Hash a password with a fresh random salt
PasswordHash hashPassword(const std::string& password) {
    AutoSeededRandomPool rng;

    PasswordHash result;
    result.salt.New(16);
    rng.GenerateBlock(result.salt, result.salt.size());
    result.hash = deriveHash(password, result.salt);
    return result;
}

// Verify a password against a stored salt and hash
bool verifyPassword(const std::string& password, const PasswordHash& stored) {
    SecByteBlock hash = deriveHash(password, stored.salt);

    // Constant-time comparison; the length is not secret
    return hash.size() == stored.hash.size() &&
           VerifyBufsEqual(hash, stored.hash, hash.size());
}

int main() {
    PasswordHash stored = hashPassword("MySecurePassword123!");

    bool accepted = verifyPassword("MySecurePassword123!", stored);
    bool rejected = !verifyPassword("WrongPassword", stored);

    std::cout << "Correct password accepted: " << (accepted ? "yes" : "no") << std::endl;
    std::cout << "Wrong password rejected: " << (rejected ? "yes" : "no") << std::endl;

    return (accepted && rejected) ? 0 : 1;
}

The example keeps the salt and hash as bytes and uses one iteration count. An application also stores the iteration count with each record, so it can be raised later, and encodes the record for its database. When it reads the count back from storage, it sets its own upper limit on it before deriving.

Example 2: Key Derivation for Encryption

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/aes.h>
#include <cryptopp/gcm.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <iostream>
#include <stdexcept>
#include <string>

std::string encryptWithPassword(const std::string& password,
                                 const std::string& plaintext) {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate salt for key derivation
    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    // Derive 32-byte key for AES-256
    SecByteBlock key(32);
    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
    pbkdf2.DeriveKey(key, key.size(),
                     0,
                     (const byte*)password.data(), password.size(),
                     salt, sizeof(salt),
                     600000);

    // Generate IV for GCM
    byte iv[12];
    rng.GenerateBlock(iv, sizeof(iv));

    // Encrypt
    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

    std::string ciphertext;
    StringSource(plaintext, true,
        new AuthenticatedEncryptionFilter(enc,
            new StringSink(ciphertext)
        )
    );

    // Format: salt || iv || ciphertext
    std::string result;
    result.assign((const char*)salt, sizeof(salt));
    result.append((const char*)iv, sizeof(iv));
    result.append(ciphertext);

    return result;
}

std::string decryptWithPassword(const std::string& password,
                                 const std::string& encrypted) {
    using namespace CryptoPP;

    if (encrypted.size() < 16 + 12 + 16) {  // salt + IV + 16-byte tag
        throw std::runtime_error("Encrypted data too short");
    }

    // Extract components
    const byte* salt = (const byte*)encrypted.data();
    const byte* iv = (const byte*)encrypted.data() + 16;
    std::string ciphertext = encrypted.substr(16 + 12);

    // Derive key
    SecByteBlock key(32);
    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
    pbkdf2.DeriveKey(key, key.size(),
                     0,
                     (const byte*)password.data(), password.size(),
                     salt, 16,
                     600000);

    // Decrypt
    GCM<AES>::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), iv, 12);

    std::string plaintext;
    StringSource(ciphertext, true,
        new AuthenticatedDecryptionFilter(dec,
            new StringSink(plaintext)
        )
    );

    return plaintext;
}

int main() {
    std::string password = "encryption_password";
    std::string message = "Secret document contents";

    std::string encrypted = encryptWithPassword(password, message);
    std::cout << "Encrypted size: " << encrypted.size() << std::endl;

    std::string decrypted = decryptWithPassword(password, encrypted);
    std::cout << "Decrypted: " << decrypted << std::endl;

    return 0;
}

Example 3: Time-Based Iterations

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    std::string password = "test_password";
    byte key[32];

    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;

    // Use time target instead of fixed iterations
    // Will iterate until ~1 second has passed
    unsigned int actualIterations = pbkdf2.DeriveKey(
        key, sizeof(key),
        0,
        (const byte*)password.data(), password.size(),
        salt, sizeof(salt),
        0,      // iterations (0 when using time)
        1.0     // target time in seconds
    );

    std::cout << "Iterations performed: " << actualIterations << std::endl;
    std::cout << "This gives you a baseline for your hardware" << std::endl;

    return 0;
}

Example 4: PBKDF2 with SHA-512

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    std::string password = "secure_password";

    // SHA-512 version - OWASP figure is 220,000 iterations
    byte key[64];
    PKCS5_PBKDF2_HMAC<SHA512> pbkdf2;
    pbkdf2.DeriveKey(key, sizeof(key),
                     0,
                     (const byte*)password.data(), password.size(),
                     salt, sizeof(salt),
                     220000);

    std::string hexKey;
    StringSource(key, sizeof(key), true,
        new HexEncoder(new StringSink(hexKey)));

    std::cout << "PBKDF2-SHA512 key: " << hexKey << std::endl;

    return 0;
}

Example 5: Deriving Multiple Keys

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    std::string password = "master_password";

    // Derive enough material for multiple keys
    // 32 bytes for encryption key + 32 bytes for MAC key
    SecByteBlock keyMaterial(64);

    PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
    pbkdf2.DeriveKey(keyMaterial, keyMaterial.size(),
                     0,
                     (const byte*)password.data(), password.size(),
                     salt, sizeof(salt),
                     600000);

    // Split into separate keys
    SecByteBlock encryptionKey(keyMaterial, 32);
    SecByteBlock macKey(keyMaterial + 32, 32);

    std::cout << "Derived encryption key (" << encryptionKey.size()
              << " bytes) and MAC key (" << macKey.size() << " bytes)" << std::endl;

    // SecByteBlock wipes its memory when it is destroyed
    return 0;
}

Iteration Count Recommendations

OWASP Recommendations

Hash FunctionIterations
SHA-256600,000 (recommended)
SHA-512220,000
SHA-11,400,000 (legacy only)

SP 800-132 recommends a minimum of 1,000 iterations and says the count should be as large as users can accept, with 10,000,000 possibly appropriate for especially critical keys; the OWASP figures above are far higher than that floor.

Choosing Iterations

// Measure on your target hardware
PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;
byte key[32], salt[16];
AutoSeededRandomPool rng;
rng.GenerateBlock(salt, sizeof(salt));

// Count the iterations that fit in about half a second
unsigned int iterations = pbkdf2.DeriveKey(
    key, sizeof(key), 0,
    (const byte*)"test", 4,
    salt, sizeof(salt),
    0,    // iterations (0 is allowed with a time budget)
    0.5   // target time in seconds
);

std::cout << "Iterations in 0.5 s: " << iterations << std::endl;

OWASP’s general rule is that calculating a hash should take less than one second. Use at least the OWASP figure even if your measurement gives fewer iterations.

PBKDF2 vs Argon2

FeaturePBKDF2Argon2
Memory hardnessNoYes
Cost parametersIteration countPasses, memory and lanes
SpecificationsRFC 8018, NIST SP 800-132RFC 9106, PHC winner
OWASP guidanceWhere FIPS-140 compliance is requiredArgon2id first

When to Use PBKDF2

  • FIPS-140 compliance required; OWASP prefers PBKDF2 in that case
  • Compatibility with existing systems
  • Argon2 not available on platform
  • Interoperability with other systems using PBKDF2

When to Use Argon2

  • New application development
  • Memory-hardness against custom-hardware attacks
  • No FIPS compliance requirement

Security Properties

PropertyValue
Security levelDepends on the password and the iteration count
Salt sizeAt least 128 random bits for SP 800-132; RFC 8018 says at least 8 octets
Output sizeUp to 2^32-1 bytes in this library; RFC 8018 allows (2^32-1) * hLen
Time complexityO(iterations) per hLen-byte block
Memory complexityO(1)

Error Handling

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <iostream>

void safeDeriveKey(const std::string& password) {
    using namespace CryptoPP;

    try {
        PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;

        AutoSeededRandomPool rng;
        byte salt[16];
        rng.GenerateBlock(salt, sizeof(salt));
        byte key[32];

        // OWASP figure for PBKDF2-HMAC-SHA256
        unsigned int iterations = 600000;

        pbkdf2.DeriveKey(key, sizeof(key),
                         0,
                         (const byte*)password.data(), password.size(),
                         salt, sizeof(salt),
                         iterations);

        // Use key...

    } catch (const Exception& e) {
        std::cerr << "PBKDF2 error: " << e.what() << std::endl;
    }
}

Thread Safety

DeriveKey() is const and creates its HMAC object and buffers inside the call, so one object can serve several threads:

// One shared object; each call keeps its own state
PKCS5_PBKDF2_HMAC<SHA256> pbkdf2;

void deriveInThread(const std::string& password,
                    const byte* salt,
                    byte* output) {
    pbkdf2.DeriveKey(output, 32, 0,
                     (const byte*)password.data(), password.size(),
                     salt, 16,
                     600000);
}

See Also

References

  1. RFC 8018: PKCS #5: Password-Based Cryptography Specification Version 2.1
  2. OWASP Password Storage Cheat Sheet
  3. NIST SP 800-132: Recommendation for Password-Based Key Derivation, Part 1: Storage Applications