Function hkdf_derive_symmetric_key
pub fn hkdf_derive_symmetric_key(
input: &Bytes,
gas_limit: u64,
) -> Result<PrecompileOutput, PrecompileErrors>
Expand description
§HKDF-based AES symmetric key derivation
This precompile implements HKDF with SHA-256. It processes the input in two stages:
- Extract: uses an HMAC-SHA256 with
input
as key material to produce a pseudo-random key (PRK). - Expand: uses a second HMAC-SHA256 to generate exactly 32 bytes for an AES-256 key.
Internally, each HMAC is two SHA-256 passes (inner + outer), like so: HMAC(K, M) = SHA256( (K ⊕ opad) || SHA256( (K ⊕ ipad) || M ) )
Where: - (K ⊕ ipad) is the key XORed with a 64-byte 0x36 pattern - (K ⊕ opad) is the same key XORed with a 64-byte 0x5C pattern
That means for a single HMAC, we have two hashing passes. HKDF then does 2 HMAC calls: one for Extract, one for Expand.
§Gas Cost
Let len(input) = n
. We do:
- Extract cost ~ 2 × SHA-256 (each pass processes
n
bytes). - Expand cost ~ 2 × SHA-256 (but for a short, fixed-size input).
We approximate the Expand step as a constant EXPAND_FIXED_COST
.
Overall:
total_cost = HMAC_SHA256_EXTRACT(n) + EXPAND_FIXED_COST
= 2 × (60 + 12 * (#words)) + ~120
where #words = ceil(n / 32)
.
§Returns
A PrecompileResult
whose bytes
field is a 32-byte key for AES-256.
§Errors
- Returns
OutOfGas
if the total cost exceeds the availablegas_limit
. - Returns
HKDF expansion error
if anything goes wrong in the internal HKDF call (rare in practice).