CodeSampleX

Пример

@noble/hashes 2.3.0: extract

Проверенный пример — npm @noble/hashes 2.3.0: extract. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: extract derives a pseudorandom key…

sha256:c9be46e032a5baee6d31619a916110f72ccf7462a0b718d0208f3d21001ecffb

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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.extract in pkg:npm/%40noble/hashes@2.3.0
Пакеты
Символы
  • @noble/hashes.extract
Окружение
node 22.23.2
Создан
2026-09-06T19:59:03Z

Контракт

  1. extract derives a pseudorandom key (PRK) from input keying material and salt conforming to RFC 5869 test vectors with SHA-256
  2. extract produces an output Uint8Array whose length exactly equals hash.outputLen
  3. extract defaults salt to HashLen zeroes when salt is undefined matching explicit zero-filled buffer
  4. extract produces different pseudorandom keys when given non-zero salt versus default undefined salt
  5. extract supports hash agility across SHA-256 and SHA-512 producing corresponding output lengths
  6. extract throws TypeError when hash argument is not a valid hasher
  7. extract throws TypeError when ikm or salt is not a Uint8Array

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Notes: Noble Hashes HKDF Extract

## Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for `@noble/hashes.extract` in `@noble/hashes@2.3.0`. Existing samples cover composite `@noble/hashes.hkdf`, `sha256`, `sha512`, `hexToBytes`, etc., but do not isolate the standalone `extract` API contract, salt defaulting behavior, parameter ordering, and error boundaries.

## Naive Model Assumption
Models often assume `extract` follows the RFC 5869 parameter order `(salt, ikm)` rather than the library's order `(hash, ikm, salt)`. Additionally, models often expect `salt` to be required or that omitting it throws an error, whereas RFC 5869 and `@noble/hashes` default `salt` to `HashLen` zeroes when `salt === undefined`. Furthermore, models often attempt to import from `@noble/hashes` or `@noble/hashes/hkdf`, failing with `ERR_MODULE_NOT_FOUND` because exports require subpath file extension `@noble/hashes/hkdf.js`.

## Failure Mode
1. Calling `extract(hash, ikm, salt)` with non-Uint8Array inputs throws `TypeError`.
2. Calling `extract(null, ikm)` throws `TypeError: expected hash wrapped by utils.createHasher`.
3. Importing from `@noble/hashes` root throws `Error: root module cannot be imported`.
4. Importing from `@noble/hashes/hkdf` fails resolution; must import from `@noble/hashes/hkdf.js`.
5. Omitting or passing `undefined` for `salt` cleanly defaults to `HashLen` zeroes per RFC 5869 §2.2 without throwing.
PROMPT.md
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.extract 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.extract

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.
csx.json
{"case":{"caseId":"case:sha256:a8ae75c6ad0047bc33f866ffaab03fe6a944ebe0a4d5c8bc495c76b5c57bbdf8","contract":["extract derives a pseudorandom key (PRK) from input keying material and salt conforming to RFC 5869 test vectors with SHA-256","extract produces an output Uint8Array whose length exactly equals hash.outputLen","extract defaults salt to HashLen zeroes when salt is undefined matching explicit zero-filled buffer","extract produces different pseudorandom keys when given non-zero salt versus default undefined salt","extract supports hash agility across SHA-256 and SHA-512 producing corresponding output lengths","extract throws TypeError when hash argument is not a valid hasher","extract throws TypeError when ikm or salt is not a Uint8Array"],"goal":"verify @noble/hashes.extract in pkg:npm/%40noble/hashes@2.3.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"symbols":["@noble/hashes.extract"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","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.extract"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-noble-hashes-extract",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-noble-hashes-extract",
      "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/"
      }
    }
  }
}
package.json
{
  "name": "sample-noble-hashes-extract",
  "version": "1.0.0",
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@noble/hashes": "2.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @noble/hashes.extract in pkg:npm/%40noble/hashes@2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40noble/hashes@2.3.0"
  ],
  "symbols": [
    "@noble/hashes.extract"
  ]
}
src/index.mjs
import { extract } from '@noble/hashes/hkdf.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { utf8ToBytes, hexToBytes, bytesToHex } from '@noble/hashes/utils.js';

export {
  extract,
  sha256,
  sha512,
  utf8ToBytes,
  hexToBytes,
  bytesToHex
};

/**
 * Extracts a pseudorandom key (PRK) from input keying material (IKM) and optional salt.
 * Implements HKDF-Extract step per RFC 5869.
 *
 * @param {import('@noble/hashes/utils.js').CHash} hash - Cryptographic hash function (e.g. sha256, sha512)
 * @param {Uint8Array} ikm - Input keying material
 * @param {Uint8Array|undefined} [salt] - Optional salt; defaults to HashLen zeroes if undefined
 * @returns {Uint8Array} Pseudorandom key (PRK) of length equal to hash.outputLen
 */
export function extractKey(hash, ikm, salt) {
  return extract(hash, ikm, salt);
}
test/contract.mjs
import assert from 'node:assert';
import {
  extract,
  extractKey,
  sha256,
  sha512,
  utf8ToBytes,
  hexToBytes,
  bytesToHex
} from '../src/index.mjs';

// ---------------------------------------------------------------------------
// 1. Contract: extract derives a pseudorandom key (PRK) from input keying
//    material and salt conforming to RFC 5869 test vectors with SHA-256
// ---------------------------------------------------------------------------
{
  // RFC 5869 Test Case 1 (SHA-256)
  const ikm = hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');
  const salt = hexToBytes('000102030405060708090a0b0c');
  const expectedPrk = '077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5';

  const prk = extract(sha256, ikm, salt);
  assert.strictEqual(bytesToHex(prk), expectedPrk, 'extract must match RFC 5869 Test Case 1 PRK');

  const prkHelper = extractKey(sha256, ikm, salt);
  assert.strictEqual(bytesToHex(prkHelper), expectedPrk, 'extractKey helper must produce identical PRK');
}

// ---------------------------------------------------------------------------
// 2. Contract: extract produces an output Uint8Array whose length exactly equals
//    hash.outputLen
// ---------------------------------------------------------------------------
{
  const ikm = utf8ToBytes('input key material');
  const salt = utf8ToBytes('salt');
  const prk256 = extract(sha256, ikm, salt);
  assert.ok(prk256 instanceof Uint8Array, 'extract output must be an instance of Uint8Array');
  assert.strictEqual(prk256.length, sha256.outputLen, 'PRK length must match hash.outputLen');
  assert.strictEqual(prk256.length, 32, 'SHA-256 PRK length must be 32 bytes');
}

// ---------------------------------------------------------------------------
// 3. Contract: extract defaults salt to HashLen zeroes when salt is undefined
//    matching explicit zero-filled buffer
// ---------------------------------------------------------------------------
{
  // RFC 5869 Test Case 3 (SHA-256, salt not provided)
  const ikm = hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');
  const expectedPrk = '19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04';

  const prkOmitted = extract(sha256, ikm);
  const prkUndefined = extract(sha256, ikm, undefined);
  const prkZeroes = extract(sha256, ikm, new Uint8Array(sha256.outputLen));

  assert.strictEqual(bytesToHex(prkOmitted), expectedPrk, 'extract with omitted salt matches RFC 5869 Test Case 3');
  assert.deepStrictEqual(prkOmitted, prkUndefined, 'omitted salt must behave identically to undefined salt');
  assert.deepStrictEqual(prkUndefined, prkZeroes, 'undefined salt must default to HashLen zeroes');
}

// ---------------------------------------------------------------------------
// 4. Contract: extract produces different pseudorandom keys when given non-zero
//    salt versus default undefined salt
// ---------------------------------------------------------------------------
{
  const ikm = hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');
  const prkDefault = extract(sha256, ikm);
  const prkCustomSalt = extract(sha256, ikm, new Uint8Array([1, 2, 3, 4]));
  assert.notDeepStrictEqual(prkDefault, prkCustomSalt, 'non-zero salt must produce a different PRK than default zero salt');
}

// ---------------------------------------------------------------------------
// 5. Contract: extract supports hash agility across SHA-256 and SHA-512
//    producing corresponding output lengths
// ---------------------------------------------------------------------------
{
  const ikm = utf8ToBytes('agile key material');
  const salt = utf8ToBytes('agile salt');

  const prk256 = extract(sha256, ikm, salt);
  const prk512 = extract(sha512, ikm, salt);

  assert.strictEqual(prk256.length, 32, 'SHA-256 PRK length must be 32 bytes');
  assert.strictEqual(prk512.length, 64, 'SHA-512 PRK length must be 64 bytes');
  assert.strictEqual(prk512.length, sha512.outputLen, 'SHA-512 PRK length must match sha512.outputLen');
  assert.notDeepStrictEqual(prk256, prk512.subarray(0, 32), 'different hash algorithms produce distinct output');
}

// ---------------------------------------------------------------------------
// 6. Contract: extract throws TypeError when hash argument is not a valid hasher
// ---------------------------------------------------------------------------
{
  assert.throws(
    () => extract(null, new Uint8Array(16)),
    { name: 'TypeError' },
    'extract must reject invalid hash instance with TypeError'
  );
  assert.throws(
    () => extract({}, new Uint8Array(16)),
    { name: 'TypeError' },
    'extract must reject plain object as hash with TypeError'
  );
}

// ---------------------------------------------------------------------------
// 7. Contract: extract throws TypeError when ikm or salt is not a Uint8Array
// ---------------------------------------------------------------------------
{
  assert.throws(
    () => extract(sha256, 'string-ikm'),
    { name: 'TypeError' },
    'extract must reject non-Uint8Array ikm with TypeError'
  );
  assert.throws(
    () => extract(sha256, new Uint8Array(16), 'string-salt'),
    { name: 'TypeError' },
    'extract must reject non-Uint8Array salt with TypeError'
  );
}

console.log('All extract contract assertions passed.');

Исходный сидер

аноним