EVP Key Derivation

From OpenSSLWiki
Revision as of 01:21, 11 July 2019 by Jwalton (talk | contribs) (Add bullet points.)

Jump to: navigation, search

Key derivation is the process of deriving one or more secret keys from a secret value such as a password or a passphrase. Several key derivation algoirthms have been standardized, and they are usually referred to a Key Derivation Functions (KDFs). KDFs include PBKDF2 from RFC 2898, HKDF form RFC 5869 and Scrypt from RFC 7914. OpenSSL provides PBKDF2, Scrypt, HKDF, ANSI X9.42 and ANSI X9.63 by way of EVP_KDF.

Not all key derivation functions are available in all versions of OpenSSL. OpenSSL 1.0.2 and below provide WWW, XXX, YYY and ZZZ. OpenSSL 1.1.0 and above provide WWW, XXX, YYY and ZZZ. TODO: fill in the pieces here and talk about changes.

HKDF key derivation

The following program derives a key using HKDF from RFC 5869. HKDF was designed by Krawczyk and Eronen, and it is state of the art in expand-then-extract key derivation algorithms. It is usually a good choice when you need a KDF. The program below was taken from the OpenSSL man pages.

HKDF takes three parameter:

  • secret - private information to use during derivation, like a password or passphrase. The parameter is set using EVP_KDF_CTRL_SET_KEY.
  • salt - possibly public information to use during derivation. salt is optional. The parameter is set using EVP_KDF_CTRL_SET_SALT.
  • info - additional, possibly public information to use during derivation. info is optional. The parameter is set using EVP_KDF_CTRL_ADD_HKDF_INFO.
#include <openssl/evp.h>
#include <openssl/kdf.h>

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
    EVP_KDF_CTX *kctx = NULL;
    unsigned char out[32];

    kctx = EVP_KDF_CTX_new_id(EVP_KDF_HKDF);

    if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_MD, EVP_sha256()) <= 0) {
    if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_SALT, "salt", (size_t)4) <= 0) {
    if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_KEY, "secret", (size_t)6) <= 0) {
    if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_ADD_HKDF_INFO, "label", (size_t)5) <= 0) {
    if (EVP_KDF_derive(kctx, out, sizeof(out)) <= 0) {
    /* Use the 32 bytes as a Key and IV */
    const unsigned char *key = out+0;
    const unsigned char  *iv = out+16;
    printf("Key: ");
    for (size_t i=0; i<16; ++i)
        printf("%02x ", key[i]);

    printf("IV:  ");
    for (size_t i=0; i<16; ++i)
        printf("%02x ", iv[i]);


    return 0;

You can compile the program using C99 with the following command.

openssl$ gcc -std=c99 test.c -o test.exe -l:libcrypto.a -pthread -ldl

Running the program results in the following output.

$ ./test.exe
Key: 2a c4 36 9f 52 59 96 f8 de 13 73 1f 56 22 4f 34
IV:  df 0e 4c 96 ca a9 3b fd ec cf 23 7b 50 39 c8 db