HKDF Key Derivation - Mijick/AES-GCM-HKDF GitHub Wiki

What is HKDF

HKDF (HMAC-based Extract-and-Expand Key Derivation Function) is used to derive secure encryption keys from a shared secret. AES-GCM-HKDF SDK implemented as described according to standard RFC 5869

Available Methods

Method Use Case
deriveKey(privateKey: publicKey: configuration:) Computes a shared secret first and then derives a key.
deriveKey(key: configuration:) Derives a key from an existing shared secret.

1️⃣ Configure

HKDF derivation requires several parameters to derive a key. Use M_HKDF_Configuration model to set-up them.

Properties

Property Type Description
hashVariant M_HashVariant The hash function used in HKDF (SHA-1, SHA-256, SHA-384, SHA-512). Recommended Choice: SHA-256
salt Data Optional. A random salt used to strengthen key derivation. Can be generated randomly with method Data.randomSalt
info Data Optional. Contextual info data to ensure key separation. Can be generated randomly with method Data.randomInfo
length Data The length of the derived key (in bytes).

Usage

  • Empty Salt and Info
let hkdfConfig = M_HKDF_Configuration(hashVariant: .sha256, length: 32)
  • Random Salt and Info
let hkdfConfig = M_HKDF_Configuration(
    hashVariant: .sha256,
    salt: .randomSalt(.sha256),
    info: .randomInfo(.sha256),
    length: 32
)
  • Custom Salt and Info
let salt: Data
let info: Data

let hkdfConfig = M_HKDF_Configuration(
    hashVariant: .sha256,
    salt: salt,
    info: info,
    length: 32 
)

2️⃣ HKDF derivation using key pair

Use this method if you have a key pair and need to generate a shared secret and derive the result.

func deriveKey(privateKey: M_KeyProtocol, publicKey: M_KeyProtocol, configuration: M_HKDF_Configuration) throws -> M_HKDF_Result

Usage

let privateKey = P256.KeyAgreement.PrivateKey()
let publicKey = privateKey.publicKey
let configuration = M_HKDF_Configuration(hashVariant: .sha256, length: 32)
let derivationInfo = try M_AES_GCM_HKDF.deriveKey(privateKey: privateKey, publicKey: publicKey, configuration: hkdfConfig)

3️⃣ HKDF derivation using existed key

Use this method if you generated shared secret on your own or just have a random key bytes.

func deriveKey(key: Data, configuration: M_HKDF_Configuration) throws -> M_HKDF_Result

Usage

let key: Data
let configuration = M_HKDF_Configuration(hashVariant: .sha256, length: 32)
let derivationInfo = try M_AES_GCM_HKDF.deriveKey(key: key, configuration: hkdfConfig)

4️⃣ Get result

M_HKDF_Result is a structured output returned by the HKDF key derivation function. It contains:

Property Type Description
salt Data The cryptographic salt used in the HKDF derivation process.
info Data The contextual info field ensuring key separation.
derivedKey Data The final securely derived key (e.g., for AES-GCM encryption).