Skip to content

HKDF

Header: #include <cryptopp/hkdf.h> | Namespace: CryptoPP Since: Crypto++ 5.6.3
Thread Safety: Not thread-safe per instance; use separate instances per thread Inherits from: KeyDerivationFunction

HKDF (HMAC-based Extract-and-Expand Key Derivation Function) is specified in RFC 5869, an Informational RFC. It uses HMAC to extract a pseudorandom key from the input key material and then expand that key into output keying material. Krawczyk’s HKDF paper analyses the construction based on the extraction and pseudorandom properties of HMAC.

Quick Example

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

int main() {
    using namespace CryptoPP;

    // Input key material (e.g., ECDH shared secret)
    SecByteBlock ikm(32);
    AutoSeededRandomPool rng;
    rng.GenerateBlock(ikm, ikm.size());

    // Salt (optional; RFC 5869 says it adds significantly to HKDF's strength)
    byte salt[16];
    rng.GenerateBlock(salt, sizeof(salt));

    // Context information
    std::string info = "application-specific-context";

    // Derive 48 bytes of key material
    SecByteBlock derivedKey(48);

    HKDF<SHA256> hkdf;
    hkdf.DeriveKey(
        derivedKey, derivedKey.size(),  // output
        ikm, ikm.size(),                // input key material
        salt, sizeof(salt),             // salt
        (const byte*)info.data(), info.size()  // info
    );

    // Split into separate keys
    SecByteBlock encKey(derivedKey, 32);      // First 32 bytes
    SecByteBlock macKey(derivedKey + 32, 16); // Next 16 bytes

    std::cout << "Derived 48 bytes of key material" << std::endl;
    std::cout << "Encryption key: 32 bytes" << std::endl;
    std::cout << "MAC key: 16 bytes" << std::endl;

    return 0;
}

Usage Guidelines

Do:

  • Use HKDF unless your protocol specifies another hash (our recommendation)
  • Provide a salt when you have one; RFC 5869 says salt adds significantly to HKDF’s strength, need not be secret, can be reused, and is ideally a random string of HashLen bytes
  • Use distinct info strings for different derived keys, so that different contexts do not derive the same keying material
  • Derive multiple keys from a single shared secret (key separation)

Avoid:

  • Using HKDF for password hashing: its extract step can concentrate entropy but cannot amplify it, and it has no slowing-down mechanism (use Argon2 instead)
  • Reusing the same info string for different purposes
  • Requesting more than 255 * HashLen bytes; RFC 5869 does not allow it and the library throws InvalidDerivedKeyLength

Template Class: HKDF

Key derivation function parameterized by hash function.

Template Parameter

template <class T>  // T = hash function (SHA256, SHA512, etc.)
class HKDF : public KeyDerivationFunction;

Common instantiations:

HKDF<SHA256> hkdf256;  // Recommended
HKDF<SHA512> hkdf512;  // High security
HKDF<SHA1>   hkdf1;    // Legacy only

Methods

DeriveKey() - Full Form

size_t DeriveKey(byte* derived, size_t derivedLen,
                 const byte* secret, size_t secretLen,
                 const byte* salt, size_t saltLen,
                 const byte* info, size_t infoLen) const;

Derive key from input key material.

Parameters:

  • derived - Output buffer for derived key
  • derivedLen - Length of derived key (max: 255 * HashLen)
  • secret - Input key material (IKM)
  • secretLen - IKM length
  • salt - Salt value (can be NULL; then HKDF uses HashLen zero bytes)
  • saltLen - Salt length (0 if NULL)
  • info - Application-specific context
  • infoLen - Info length (can be 0)

Returns: 1 (always, unlike PBKDF which returns iteration count)

Example:

HKDF<SHA256> hkdf;
AutoSeededRandomPool rng;

SecByteBlock ikm(32);      // Input key material: normally a shared secret, random here
rng.GenerateBlock(ikm, ikm.size());
byte salt[16];             // Salt
rng.GenerateBlock(salt, sizeof(salt));
std::string info = "app-context";
SecByteBlock output(64);   // Derive 64 bytes

hkdf.DeriveKey(
    output, output.size(),
    ikm, ikm.size(),
    salt, sizeof(salt),
    (const byte*)info.data(), info.size()
);

MaxDerivedKeyLength()

size_t MaxDerivedKeyLength() const;

Get maximum output length.

Returns: 255 * HashLen (e.g., 8160 bytes for SHA256)

Example:

HKDF<SHA256> hkdf;
size_t maxLen = hkdf.MaxDerivedKeyLength();
// Returns: 255 * 32 = 8160 bytes

Complete Example: Key Separation

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

using namespace CryptoPP;

class DerivedKeys {
public:
    SecByteBlock aesKey;
    SecByteBlock hmacKey;
    SecByteBlock ivKey;

    static DerivedKeys fromSharedSecret(const SecByteBlock& sharedSecret,
                                        const std::string& context) {
        DerivedKeys keys;

        // Derive separate keys using different info strings
        HKDF<SHA256> hkdf;

        // AES key (32 bytes)
        keys.aesKey.New(32);
        std::string aesInfo = context + ":aes";
        hkdf.DeriveKey(
            keys.aesKey, keys.aesKey.size(),
            sharedSecret, sharedSecret.size(),
            nullptr, 0,  // no salt
            (const byte*)aesInfo.data(), aesInfo.size()
        );

        // HMAC key (32 bytes)
        keys.hmacKey.New(32);
        std::string hmacInfo = context + ":hmac";
        hkdf.DeriveKey(
            keys.hmacKey, keys.hmacKey.size(),
            sharedSecret, sharedSecret.size(),
            nullptr, 0,
            (const byte*)hmacInfo.data(), hmacInfo.size()
        );

        // IV generation key (16 bytes)
        keys.ivKey.New(16);
        std::string ivInfo = context + ":iv";
        hkdf.DeriveKey(
            keys.ivKey, keys.ivKey.size(),
            sharedSecret, sharedSecret.size(),
            nullptr, 0,
            (const byte*)ivInfo.data(), ivInfo.size()
        );

        return keys;
    }
};

int main() {
    AutoSeededRandomPool rng;

    // Simulate ECDH shared secret
    SecByteBlock sharedSecret(32);
    rng.GenerateBlock(sharedSecret, sharedSecret.size());

    // Derive separate keys for encryption, MAC, IV
    DerivedKeys keys = DerivedKeys::fromSharedSecret(
        sharedSecret,
        "secure-channel-v1"
    );

    std::cout << "Derived keys from shared secret:" << std::endl;
    std::cout << "AES key: " << keys.aesKey.size() << " bytes" << std::endl;
    std::cout << "HMAC key: " << keys.hmacKey.size() << " bytes" << std::endl;
    std::cout << "IV key: " << keys.ivKey.size() << " bytes" << std::endl;

    // Keys are cryptographically independent
    // Safe to use for different purposes

    return 0;
}

Complete Example: ECDH + HKDF

This example turns an ECDH shared secret into an encryption key and a MAC key. It does not authenticate the public keys: in a protocol, each side must check that the public key it received belongs to the intended peer, for example with a signature or a certificate, before using the derived keys.

#include <cryptopp/hkdf.h>
#include <cryptopp/sha.h>
#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/misc.h>
#include <iostream>
#include <stdexcept>
#include <string>

using namespace CryptoPP;

struct SessionKeys {
    SecByteBlock encryptionKey;
    SecByteBlock macKey;
};

SessionKeys deriveSessionKeys(const ECDH<ECP>::Domain& domain,
                              const SecByteBlock& privateKey,
                              const SecByteBlock& peerPublicKey,
                              const std::string& context) {
    // Perform ECDH key agreement
    SecByteBlock sharedSecret(domain.AgreedValueLength());

    if (!domain.Agree(sharedSecret, privateKey, peerPublicKey)) {
        throw std::runtime_error("ECDH agreement failed");
    }

    // Derive keys using HKDF
    SecByteBlock derivedKeys(64);  // 32 + 32
    HKDF<SHA256> hkdf;

    hkdf.DeriveKey(
        derivedKeys, derivedKeys.size(),
        sharedSecret, sharedSecret.size(),
        nullptr, 0,  // no salt: HKDF uses HashLen zero bytes
        (const byte*)context.data(), context.size()
    );

    // Split derived keys
    SessionKeys keys;
    keys.encryptionKey.Assign(derivedKeys, 32);
    keys.macKey.Assign(derivedKeys + 32, 32);
    return keys;
}

int main() {
    AutoSeededRandomPool rng;

    // Create ECDH domain (P-256)
    ECDH<ECP>::Domain domain(ASN1::secp256r1());

    // Alice's key pair
    SecByteBlock alicePrivate(domain.PrivateKeyLength());
    SecByteBlock alicePublic(domain.PublicKeyLength());
    domain.GenerateKeyPair(rng, alicePrivate, alicePublic);

    // Bob's key pair
    SecByteBlock bobPrivate(domain.PrivateKeyLength());
    SecByteBlock bobPublic(domain.PublicKeyLength());
    domain.GenerateKeyPair(rng, bobPrivate, bobPublic);

    // Each side combines its own private key with the other's public key
    SessionKeys aliceKeys = deriveSessionKeys(
        domain, alicePrivate, bobPublic, "chat-session-2024"
    );
    SessionKeys bobKeys = deriveSessionKeys(
        domain, bobPrivate, alicePublic, "chat-session-2024"
    );

    // Verify both sides derived same keys
    bool encMatch = VerifyBufsEqual(
        aliceKeys.encryptionKey.data(),
        bobKeys.encryptionKey.data(),
        32
    );

    bool macMatch = VerifyBufsEqual(
        aliceKeys.macKey.data(),
        bobKeys.macKey.data(),
        32
    );

    std::cout << "Both sides derived the same keys: "
              << (encMatch && macMatch ? "YES" : "NO") << std::endl;

    return (encMatch && macMatch) ? 0 : 1;
}

Complete Example: Password-Based Key with Salt

#include <cryptopp/hkdf.h>
#include <cryptopp/sha.h>
#include <cryptopp/argon2.h>
#include <cryptopp/osrng.h>
#include <iostream>

using namespace CryptoPP;

// Proper password-based key derivation combines Argon2 + HKDF
class PasswordDerivedKeys {
public:
    static SecByteBlock deriveFromPassword(
        const std::string& password,
        const byte* salt, size_t saltLen,
        size_t outputLen) {

        // Step 1: Hash password with Argon2id (slow, memory-hard)
        Argon2 argon2;
        SecByteBlock passwordHash(32);

        argon2.DeriveKey(
            passwordHash, passwordHash.size(),
            (const byte*)password.data(), password.size(),
            salt, saltLen,
            3, 65536, 4  // t=3, m=64 MiB, p=4 (RFC 9106 second option)
        );

        std::cout << "Argon2 password hash: " << passwordHash.size()
                  << " bytes" << std::endl;

        // Step 2: Expand with HKDF (fast, generate multiple keys)
        HKDF<SHA256> hkdf;
        SecByteBlock output(outputLen);

        std::string info = "application-keys-v1";
        hkdf.DeriveKey(
            output, output.size(),
            passwordHash, passwordHash.size(),
            salt, saltLen,
            (const byte*)info.data(), info.size()
        );

        return output;
    }
};

int main() {
    AutoSeededRandomPool rng;

    std::string password = "correct horse battery staple";

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

    // Derive 64 bytes for encryption + MAC keys
    SecByteBlock keys = PasswordDerivedKeys::deriveFromPassword(
        password, salt, sizeof(salt), 64
    );

    std::cout << "Derived " << keys.size() << " bytes from password" << std::endl;

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

    std::cout << "Encryption key: " << encKey.size() << " bytes" << std::endl;
    std::cout << "MAC key: " << macKey.size() << " bytes" << std::endl;

    return 0;
}

Salt Behaviour

A NULL salt and an empty (non-NULL, zero-length) salt give the same output. RFC 5869 replaces a missing salt with HashLen zero bytes, and the library does the same for a NULL pointer. HMAC pads a key shorter than the hash block size with zero bytes, and the library’s HMAC does so too, so an empty salt and HashLen zero bytes produce the same HMAC key and the same pseudorandom key.

HKDF<SHA256> hkdf;

// NULL salt: HKDF uses HashLen zero bytes
hkdf.DeriveKey(output, outLen, ikm, ikmLen,
               nullptr, 0,
               info, infoLen);

// Empty salt (non-NULL pointer, zero length): same output as NULL
byte dummy = 0;
hkdf.DeriveKey(output, outLen, ikm, ikmLen,
               &dummy, 0,
               info, infoLen);

// Explicit salt (recommended)
byte salt[16] = { /* ... */ };
hkdf.DeriveKey(output, outLen, ikm, ikmLen,
               salt, sizeof(salt),
               info, infoLen);

Recommendation: Provide an explicit salt when you have one.

Info String Usage

The info parameter binds derived keys to specific contexts:

HKDF<SHA256> hkdf;
AutoSeededRandomPool rng;
SecByteBlock ikm(32), output(32);
rng.GenerateBlock(ikm, ikm.size());  // stand-in for your input key material

// Different info strings give different keys
std::string info1 = "encryption";
hkdf.DeriveKey(output, 32, ikm, 32, nullptr, 0,
               (const byte*)info1.data(), info1.size());
SecByteBlock encKey = output;

std::string info2 = "authentication";
hkdf.DeriveKey(output, 32, ikm, 32, nullptr, 0,
               (const byte*)info2.data(), info2.size());
SecByteBlock macKey = output;

// encKey and macKey differ because their info strings differ

Best practices:

  • Include version: "myapp-v1:encryption"
  • Include purpose: "client-to-server-key"
  • Include protocol: "TLS-1.3-handshake-key"

Cost

HKDF computes one HMAC for the extract step and one HMAC per HashLen bytes of output for the expand step.

Use HKDF for key derivation, Argon2 for password hashing.

Security

Security Properties

  • Extraction: The extract step concentrates the entropy of the input key material into a pseudorandom key; it cannot amplify entropy
  • Expansion: The expand step generates up to 255 * HashLen bytes from that key
  • Analysis: Krawczyk’s paper analyses HKDF based on the extraction and pseudorandom properties of HMAC
  • Specification: RFC 5869; NIST SP 800-56C Rev. 2 section 5 specifies a two-step extraction-then-expansion procedure of the same shape, with HMAC as one extraction option
  • Protocols: The TLS 1.3 key schedule uses HKDF-Extract and HKDF-Expand

Hash Function Selection

// Recommended default
HKDF<SHA256> hkdf256;

// Larger HashLen and output limit
HKDF<SHA512> hkdf512;

// Legacy only: SHA-1 (avoid for new applications)
HKDF<SHA1> hkdf1;

Security Best Practices

  1. Use Different Info for Different Keys:

    // CORRECT - different info strings
    hkdf.DeriveKey(encKey, 32, ikm, ikm.size(), salt, sizeof(salt),
                   (const byte*)"encryption", 10);
    hkdf.DeriveKey(macKey, 32, ikm, ikm.size(), salt, sizeof(salt),
                   (const byte*)"authentication", 14);
    
    // WRONG - the same info string gives identical keys
    hkdf.DeriveKey(encKey, 32, ikm, ikm.size(), salt, sizeof(salt),
                   (const byte*)"keys", 4);
    hkdf.DeriveKey(macKey, 32, ikm, ikm.size(), salt, sizeof(salt),
                   (const byte*)"keys", 4);
  2. Provide Salt When Available:

    // GOOD - with salt
    hkdf.DeriveKey(key, keyLen, ikm, ikm.size(), salt, saltLen, info, infoLen);
    
    // ACCEPTABLE - no salt; RFC 5869 still recommends one when available
    hkdf.DeriveKey(key, keyLen, ikm, ikm.size(), nullptr, 0, info, infoLen);
  3. Don’t Use for Password Hashing:

    // WRONG - HKDF for passwords
    HKDF<SHA256> hkdf;
    hkdf.DeriveKey(key, keyLen, (const byte*)password.data(), password.size(),
                   salt, saltLen, info, infoLen);
    
    // CORRECT - Argon2 then HKDF
    Argon2 argon2;
    argon2.DeriveKey(hash, hashLen, (const byte*)password.data(), password.size(),
                     salt, saltLen, 3, 65536, 4);
    hkdf.DeriveKey(key, keyLen, hash, hashLen, salt, saltLen, info, infoLen);

Thread Safety

DeriveKey() is const and uses only local HMAC state, but the class is not documented as thread-safe; use separate instances per thread.

When to Use HKDF

Use HKDF for:

  1. Key Derivation from Shared Secrets - After ECDH/X25519 key agreement
  2. Key Separation - Derive encryption, MAC, IV keys from one secret
  3. Key Expansion - Generate multiple keys from single master key
  4. Protocol Key Derivation - for example, the TLS 1.3 key schedule
  5. After Argon2 - Expand password hash into multiple keys

Don’t use HKDF for:

  1. Password Hashing - Use Argon2id instead
  2. Low-Entropy Secrets - HKDF cannot amplify entropy; use Argon2 or PBKDF2 first
  3. Random Number Generation - Use AutoSeededRandomPool

HKDF vs Argon2 vs PBKDF2

KDFDeliberately slowUse Case
HKDFNoHigh-entropy secrets (ECDH, etc.)
Argon2Yes, memory-hardPassword hashing
PBKDF2Yes, iteratedLegacy password hashing

Decision tree:

  • High-entropy secret (ECDH, random key): use HKDF
  • Password: use Argon2id
  • Legacy password system: use PBKDF2

Exceptions

  • InvalidDerivedKeyLength - derivedLen is greater than 255 * HashLen

See Also

  • Argon2 - For password hashing
  • HMAC - Underlying primitive
  • X25519 - Key exchange (use with HKDF)
  • SHA-256 - Recommended hash function

References

  1. RFC 5869: HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
  2. Krawczyk: Cryptographic Extraction and Key Derivation: The HKDF Scheme, CRYPTO 2010
  3. RFC 2104: HMAC: Keyed-Hashing for Message Authentication
  4. NIST SP 800-56C Rev. 2: Recommendation for Key-Derivation Methods in Key-Establishment Schemes
  5. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3