샘플
@noble/hashes 2.3.0: hkdf
검증된 샘플 — npm @noble/hashes 2.3.0: hkdf. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: hkdf extracts and expands key material according to RFC…
sha256:316811786d71c963f1896da3f97c310574a8c94ee19996bd7251db49dbf1e457
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 npm
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-09-06 |
케이스
HOW- 목표
- verify @noble/hashes.hkdf in pkg:npm/%40noble/hashes@2.3.0
- 심벌
-
- @noble/hashes.hkdf
- 생성일
- 2026-09-06T15:43:05Z
컨트랙트
- hkdf extracts and expands key material according to RFC 5869 test vectors with SHA-256
- extract and hkdf default to HashLen zeroes when salt is undefined
- expand and hkdf return an empty Uint8Array when requested output length is 0
- expand and hkdf throw an error when requested output length exceeds 255 * HashLen
- expand throws an error when pseudorandom key length is less than HashLen
- hkdf supports hash agility across SHA-256 and SHA-512 producing deterministic output matching extract and expand steps
파일
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
소스
# Notes: Noble Hashes HKDF Key Derivation
## Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for `@noble/hashes.hkdf` in `@noble/hashes@2.3.0`. Existing samples for `@noble/hashes` cover general cryptographic hashing, HMAC, and legacy primitives, but lack focused contract verification for RFC 5869 HKDF extraction, expansion, length boundaries, and salt defaulting behavior.
## Naive Model Assumption
Models and developers often assume that HKDF only exposes a single composite function rather than distinct `extract` and `expand` primitives, or that passing `undefined` for `salt` causes a runtime validation error rather than defaulting to `HashLen` zeroes per RFC 5869 §2.2. Additionally, models frequently misunderstand the strict length bounds enforced by RFC 5869 (maximum output length of `255 * HashLen`, zero length returning empty buffer) and the requirement that `prk` must be at least `HashLen` octets.
## Failure Mode
1. Passing a PRK shorter than `hash.outputLen` to `expand()` throws `Error: "prk" must be at least HashLen octets`.
2. Requesting an output length greater than `255 * hash.outputLen` throws `Error: Length must be <= 255*HashLen`.
3. Omitting or passing `undefined` for `salt` defaults cleanly to `new Uint8Array(hash.outputLen)` zeroes per RFC 5869 §2.2.
4. Requesting `length = 0` produces an empty `Uint8Array` rather than throwing.
5. `hkdf()` combines extraction and expansion in one call, exactly matching the result of `expand(hash, extract(hash, ikm, salt), info, length)`.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify @noble/hashes.hkdf in pkg:npm/%40noble/hashes@2.3.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/%40noble/hashes@2.3.0
Demonstrate these symbols/APIs:
- @noble/hashes.hkdf
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:c026f92690b838d579af3042cb5d93af31d2d83442dda664162934b86efa6140","contract":["hkdf extracts and expands key material according to RFC 5869 test vectors with SHA-256","extract and hkdf default to HashLen zeroes when salt is undefined","expand and hkdf return an empty Uint8Array when requested output length is 0","expand and hkdf throw an error when requested output length exceeds 255 * HashLen","expand throws an error when pseudorandom key length is less than HashLen","hkdf supports hash agility across SHA-256 and SHA-512 producing deterministic output matching extract and expand steps"],"goal":"verify @noble/hashes.hkdf in pkg:npm/%40noble/hashes@2.3.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"symbols":["@noble/hashes.hkdf"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"subject":"pkg:npm/%40noble/hashes@2.3.0","symbols":["@noble/hashes.hkdf"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-noble-hashes-hkdf",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-noble-hashes-hkdf",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"@noble/hashes": "2.3.0"
}
},
"node_modules/@noble/hashes": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",
"integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
}
}
}
{
"name": "sample-noble-hashes-hkdf",
"version": "1.0.0",
"type": "module",
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@noble/hashes": "2.3.0"
}
}
{
"schemaVersion": 1,
"goal": "verify @noble/hashes.hkdf in pkg:npm/%40noble/hashes@2.3.0",
"kind": "HOW",
"packages": [
"pkg:npm/%40noble/hashes@2.3.0"
],
"symbols": [
"@noble/hashes.hkdf"
]
}
import { hkdf, extract, expand } from '@noble/hashes/hkdf.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { utf8ToBytes, hexToBytes, bytesToHex } from '@noble/hashes/utils.js';
export {
hkdf,
extract,
expand,
sha256,
sha512,
utf8ToBytes,
hexToBytes,
bytesToHex
};
/**
* Derives output keying material (OKM) using HKDF (RFC 5869).
* Combines extract and expand into a single step.
*
* @param {import('@noble/hashes/utils.js').CHash} hash - Underlying cryptographic hash function.
* @param {Uint8Array} ikm - Input keying material.
* @param {Uint8Array|undefined} [salt] - Salt value; if omitted or undefined, defaults to HashLen zeroes.
* @param {Uint8Array|undefined} [info] - Context/application specific info; if omitted, defaults to empty bytes.
* @param {number} length - Desired key length in bytes (<= 255 * HashLen).
* @returns {Uint8Array} Derived output keying material.
*/
export function deriveKey(hash, ikm, salt, info, length) {
return hkdf(hash, ikm, salt, info, length);
}
/**
* Extracts a pseudorandom key (PRK) from input keying material and optional salt.
*
* @param {import('@noble/hashes/utils.js').CHash} hash - Underlying cryptographic hash function.
* @param {Uint8Array} ikm - Input keying material.
* @param {Uint8Array|undefined} [salt] - Salt value; defaults to HashLen zeroes if undefined.
* @returns {Uint8Array} Pseudorandom key (PRK) of length equal to hash.outputLen.
*/
export function extractPrk(hash, ikm, salt) {
return extract(hash, ikm, salt);
}
/**
* Expands a pseudorandom key (PRK) into output keying material (OKM).
*
* @param {import('@noble/hashes/utils.js').CHash} hash - Underlying cryptographic hash function.
* @param {Uint8Array} prk - Pseudorandom key with length at least HashLen.
* @param {Uint8Array|undefined} [info] - Optional context and application specific information.
* @param {number} [length=32] - Output keying material length in bytes (0 <= length <= 255 * HashLen).
* @returns {Uint8Array} Output keying material (OKM) of requested length.
*/
export function expandPrk(hash, prk, info, length = 32) {
return expand(hash, prk, info, length);
}
import assert from 'node:assert';
import {
hkdf,
extract,
expand,
sha256,
sha512,
utf8ToBytes,
hexToBytes,
bytesToHex,
deriveKey,
extractPrk,
expandPrk
} from '../src/index.mjs';
// ---------------------------------------------------------------------------
// 1. Contract: hkdf extracts and expands key material according to RFC 5869
// test vectors with SHA-256
// ---------------------------------------------------------------------------
{
// RFC 5869 Test Case 1 (SHA-256)
const ikm = hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');
const salt = hexToBytes('000102030405060708090a0b0c');
const info = hexToBytes('f0f1f2f3f4f5f6f7f8f9');
const length = 42;
const expectedPrk = '077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5';
const expectedOkm = '3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865';
const prk = extract(sha256, ikm, salt);
assert.strictEqual(bytesToHex(prk), expectedPrk, 'extract should produce RFC 5869 Test Case 1 PRK');
const okm = expand(sha256, prk, info, length);
assert.strictEqual(bytesToHex(okm), expectedOkm, 'expand should produce RFC 5869 Test Case 1 OKM');
const directOkm = hkdf(sha256, ikm, salt, info, length);
assert.strictEqual(bytesToHex(directOkm), expectedOkm, 'hkdf one-step should produce identical OKM to extract followed by expand');
const helperOkm = deriveKey(sha256, ikm, salt, info, length);
assert.strictEqual(bytesToHex(helperOkm), expectedOkm, 'deriveKey helper should produce expected OKM');
}
// ---------------------------------------------------------------------------
// 2. Contract: extract and hkdf default to HashLen zeroes when salt is undefined
// ---------------------------------------------------------------------------
{
const sampleIkm = utf8ToBytes('input key material');
const prkUndefinedSalt = extract(sha256, sampleIkm, undefined);
const prkZeroHashLenSalt = extract(sha256, sampleIkm, new Uint8Array(sha256.outputLen));
assert.deepStrictEqual(prkUndefinedSalt, prkZeroHashLenSalt, 'undefined salt must default to HashLen zeroes per RFC 5869');
const okmUndefinedSalt = hkdf(sha256, sampleIkm, undefined, utf8ToBytes('context'), 32);
const okmZeroHashLenSalt = hkdf(sha256, sampleIkm, new Uint8Array(32), utf8ToBytes('context'), 32);
assert.deepStrictEqual(okmUndefinedSalt, okmZeroHashLenSalt, 'hkdf with undefined salt matches salt with HashLen zeros');
}
// ---------------------------------------------------------------------------
// 3. Contract: expand and hkdf return an empty Uint8Array when requested
// output length is 0
// ---------------------------------------------------------------------------
{
const dummyPrk = new Uint8Array(sha256.outputLen);
const emptyOkm = expand(sha256, dummyPrk, undefined, 0);
assert.strictEqual(emptyOkm.length, 0, 'expand with length 0 should return empty Uint8Array');
assert.ok(emptyOkm instanceof Uint8Array);
const emptyHkdf = hkdf(sha256, new Uint8Array(16), undefined, undefined, 0);
assert.strictEqual(emptyHkdf.length, 0, 'hkdf with length 0 should return empty Uint8Array');
assert.ok(emptyHkdf instanceof Uint8Array);
}
// ---------------------------------------------------------------------------
// 4. Contract: expand and hkdf throw an error when requested output length
// exceeds 255 * HashLen
// ---------------------------------------------------------------------------
{
const prk = new Uint8Array(sha256.outputLen);
const maxSha256Len = 255 * sha256.outputLen;
assert.throws(
() => expand(sha256, prk, undefined, maxSha256Len + 1),
{ message: 'Length must be <= 255*HashLen' },
'expand should reject lengths exceeding 255 * HashLen'
);
assert.throws(
() => hkdf(sha256, new Uint8Array(16), undefined, undefined, maxSha256Len + 1),
{ message: 'Length must be <= 255*HashLen' },
'hkdf should reject lengths exceeding 255 * HashLen'
);
}
// ---------------------------------------------------------------------------
// 5. Contract: expand throws an error when pseudorandom key length is less
// than HashLen
// ---------------------------------------------------------------------------
{
assert.throws(
() => expand(sha256, new Uint8Array(sha256.outputLen - 1), undefined, 32),
{ message: '"prk" must be at least HashLen octets' },
'expand should reject PRK shorter than HashLen octets'
);
}
// ---------------------------------------------------------------------------
// 6. Contract: hkdf supports hash agility across SHA-256 and SHA-512
// producing deterministic output matching extract and expand steps
// ---------------------------------------------------------------------------
{
const ikm512 = utf8ToBytes('sha512 test key');
const salt512 = utf8ToBytes('sha512 salt');
const info512 = utf8ToBytes('sha512 info');
const okm512 = hkdf(sha512, ikm512, salt512, info512, 64);
assert.strictEqual(okm512.length, 64, 'hkdf with SHA-512 should produce 64 bytes of output');
const prk512 = extractPrk(sha512, ikm512, salt512);
assert.strictEqual(prk512.length, 64, 'extract with SHA-512 should produce 64 bytes PRK');
const okm512TwoStep = expandPrk(sha512, prk512, info512, 64);
assert.deepStrictEqual(okm512, okm512TwoStep, 'hkdf with SHA-512 matches two-step extract and expand');
}
console.log('All HKDF contract tests passed successfully.');
오리진 시더
익명