CodeSampleX

Пример

@noble/hashes 2.3.0: pbkdf2

Проверенный пример — npm @noble/hashes 2.3.0: pbkdf2. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: pbkdf2 derives RFC 6070 HMAC-SHA256…

sha256:78fe5f395a28a73d78240f49241888ea2916757d6064a53da20b8eb1089a6234

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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.pbkdf2 in pkg:npm/%40noble/hashes@2.3.0
Пакеты
Символы
  • @noble/hashes.pbkdf2
Создан
2026-09-06T23:17:04Z

Контракт

  1. pbkdf2 derives RFC 6070 HMAC-SHA256 test vectors with string password and salt
  2. pbkdf2 accepts Uint8Array binary inputs for password and salt matching string results
  3. pbkdf2Async derives identical cryptographic keys to synchronous pbkdf2 across configurable work factors
  4. pbkdf2 defaults to 32-byte derived key length and supports custom output sizes via dkLen
  5. pbkdf2 supports different hash functions including sha256 and sha512 from noble hashes
  6. pbkdf2 validates options throwing descriptive errors when iteration count or dkLen is less than 1

Файлы

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

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

Исходный код

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.pbkdf2 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.pbkdf2

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:d2456918fac54f7db4e6108f1cb4b1d4624ccd03ecb4edee575132c9f41378d9","contract":["pbkdf2 derives RFC 6070 HMAC-SHA256 test vectors with string password and salt","pbkdf2 accepts Uint8Array binary inputs for password and salt matching string results","pbkdf2Async derives identical cryptographic keys to synchronous pbkdf2 across configurable work factors","pbkdf2 defaults to 32-byte derived key length and supports custom output sizes via dkLen","pbkdf2 supports different hash functions including sha256 and sha512 from noble hashes","pbkdf2 validates options throwing descriptive errors when iteration count or dkLen is less than 1"],"goal":"verify @noble/hashes.pbkdf2 in pkg:npm/%40noble/hashes@2.3.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"symbols":["@noble/hashes.pbkdf2"]},"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.pbkdf2"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-noble-hashes-pbkdf2",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-noble-hashes-pbkdf2",
      "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-pbkdf2",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for @noble/hashes.pbkdf2",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@noble/hashes": "2.3.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @noble/hashes.pbkdf2 in pkg:npm/%40noble/hashes@2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40noble/hashes@2.3.0"
  ],
  "symbols": [
    "@noble/hashes.pbkdf2"
  ]
}
src/index.mjs
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { bytesToHex } from '@noble/hashes/utils.js';

/**
 * Derives a cryptographic key using PBKDF2.
 * @param {import('@noble/hashes/utils.js').CHash} hash - Hash function (e.g. sha256)
 * @param {string|Uint8Array} password - Password input
 * @param {string|Uint8Array} salt - Cryptographic salt
 * @param {{ c: number, dkLen?: number, asyncTick?: number }} options - PBKDF2 options
 * @returns {Uint8Array} Derived key bytes
 */
export function deriveKey(hash, password, salt, options) {
  return pbkdf2(hash, password, salt, options);
}

/**
 * Asynchronously derives a cryptographic key using PBKDF2.
 * @param {import('@noble/hashes/utils.js').CHash} hash - Hash function (e.g. sha256)
 * @param {string|Uint8Array} password - Password input
 * @param {string|Uint8Array} salt - Cryptographic salt
 * @param {{ c: number, dkLen?: number, asyncTick?: number }} options - PBKDF2 options
 * @returns {Promise<Uint8Array>} Derived key bytes
 */
export async function deriveKeyAsync(hash, password, salt, options) {
  return pbkdf2Async(hash, password, salt, options);
}

/**
 * Derives a key and returns it as a hexadecimal string.
 * @param {import('@noble/hashes/utils.js').CHash} hash - Hash function
 * @param {string|Uint8Array} password - Password input
 * @param {string|Uint8Array} salt - Cryptographic salt
 * @param {{ c: number, dkLen?: number }} options - PBKDF2 options
 * @returns {string} Hexadecimal key string
 */
export function deriveKeyHex(hash, password, salt, options) {
  const bytes = pbkdf2(hash, password, salt, options);
  return bytesToHex(bytes);
}

/**
 * Verifies if a password and salt match an expected derived key using constant-time comparison.
 * @param {import('@noble/hashes/utils.js').CHash} hash - Hash function
 * @param {string|Uint8Array} password - Password input
 * @param {string|Uint8Array} salt - Cryptographic salt
 * @param {Uint8Array} expectedKey - Expected key bytes
 * @param {{ c: number, dkLen?: number }} options - PBKDF2 options
 * @returns {boolean} True if derived key matches expected key
 */
export function verifyDerivedKey(hash, password, salt, expectedKey, options) {
  const derived = pbkdf2(hash, password, salt, { ...options, dkLen: expectedKey.length });
  if (derived.length !== expectedKey.length) return false;
  let diff = 0;
  for (let i = 0; i < derived.length; i++) {
    diff |= derived[i] ^ expectedKey[i];
  }
  return diff === 0;
}

export { pbkdf2, pbkdf2Async, sha256, sha512 };
test/contract.mjs
import assert from 'node:assert';
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
import {
  deriveKey,
  deriveKeyAsync,
  deriveKeyHex,
  verifyDerivedKey,
} from '../src/index.mjs';

// Contract Assertion 1:
// pbkdf2 derives RFC 6070 HMAC-SHA256 test vectors with string password and salt
{
  // RFC 6070 test vector 1: c = 1, dkLen = 32
  const key1 = pbkdf2(sha256, 'password', 'salt', { c: 1, dkLen: 32 });
  assert.strictEqual(key1 instanceof Uint8Array, true, 'output must be Uint8Array');
  assert.strictEqual(key1.length, 32, 'derived key length must be 32 bytes');
  assert.strictEqual(
    bytesToHex(key1),
    '120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b',
    'RFC 6070 vector 1 digest mismatch'
  );

  // RFC 6070 test vector 2: c = 2, dkLen = 32
  const key2 = pbkdf2(sha256, 'password', 'salt', { c: 2, dkLen: 32 });
  assert.strictEqual(
    bytesToHex(key2),
    'ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43',
    'RFC 6070 vector 2 digest mismatch'
  );

  // Verify helper deriveKey and deriveKeyHex match
  assert.strictEqual(bytesToHex(deriveKey(sha256, 'password', 'salt', { c: 1, dkLen: 32 })), bytesToHex(key1));
  assert.strictEqual(deriveKeyHex(sha256, 'password', 'salt', { c: 1, dkLen: 32 }), bytesToHex(key1));
}

// Contract Assertion 2:
// pbkdf2 accepts Uint8Array binary inputs for password and salt matching string results
{
  const passwordBytes = utf8ToBytes('password');
  const saltBytes = utf8ToBytes('salt');
  const keyFromBytes = pbkdf2(sha256, passwordBytes, saltBytes, { c: 2, dkLen: 32 });
  const keyFromString = pbkdf2(sha256, 'password', 'salt', { c: 2, dkLen: 32 });
  assert.deepStrictEqual(keyFromBytes, keyFromString, 'Uint8Array inputs must match string inputs');

  // Also verify password with non-ASCII UTF-8 encoding
  const utf8Password = 'p@sswørd🔑';
  const utf8Salt = 's@lt🧂';
  const keyUtf8Str = pbkdf2(sha256, utf8Password, utf8Salt, { c: 5, dkLen: 32 });
  const keyUtf8Bytes = pbkdf2(sha256, utf8ToBytes(utf8Password), utf8ToBytes(utf8Salt), { c: 5, dkLen: 32 });
  assert.deepStrictEqual(keyUtf8Str, keyUtf8Bytes, 'Unicode inputs must match between string and bytes');
}

// Contract Assertion 3:
// pbkdf2Async derives identical cryptographic keys to synchronous pbkdf2 across configurable work factors
{
  const cValues = [1, 2, 10, 50];
  for (const c of cValues) {
    const syncKey = pbkdf2(sha256, 'async-password', 'async-salt', { c, dkLen: 32 });
    const asyncKey = await pbkdf2Async(sha256, 'async-password', 'async-salt', { c, dkLen: 32 });
    assert.deepStrictEqual(asyncKey, syncKey, `async output must match sync output for c=${c}`);

    // Test with custom asyncTick yield interval
    const asyncKeyWithTick = await pbkdf2Async(sha256, 'async-password', 'async-salt', {
      c,
      dkLen: 32,
      asyncTick: 2,
    });
    assert.deepStrictEqual(asyncKeyWithTick, syncKey, 'asyncTick must not alter derived output');

    // Test helper deriveKeyAsync
    const helperAsyncKey = await deriveKeyAsync(sha256, 'async-password', 'async-salt', { c, dkLen: 32 });
    assert.deepStrictEqual(helperAsyncKey, syncKey, 'helper deriveKeyAsync must match sync');
  }
}

// Contract Assertion 4:
// pbkdf2 defaults to 32-byte derived key length and supports custom output sizes via dkLen
{
  // Default dkLen is 32 bytes
  const defaultKey = pbkdf2(sha256, 'password', 'salt', { c: 1 });
  assert.strictEqual(defaultKey.length, 32, 'default dkLen must be 32 bytes');

  // Custom dkLen shorter than hash output (16 bytes)
  const shortKey = pbkdf2(sha256, 'password', 'salt', { c: 1, dkLen: 16 });
  assert.strictEqual(shortKey.length, 16, 'custom dkLen 16 must produce 16 bytes');
  assert.deepStrictEqual(shortKey, defaultKey.subarray(0, 16), 'short dkLen must equal prefix of default key');

  // Custom dkLen longer than hash output (64 bytes, spanning multiple PRF blocks)
  const longKey = pbkdf2(sha256, 'password', 'salt', { c: 1, dkLen: 64 });
  assert.strictEqual(longKey.length, 64, 'custom dkLen 64 must produce 64 bytes');
  assert.deepStrictEqual(longKey.subarray(0, 32), defaultKey, 'first block must equal default 32-byte key');
}

// Contract Assertion 5:
// pbkdf2 supports different hash functions including sha256 and sha512 from noble hashes
{
  const sha256Key = pbkdf2(sha256, 'multi-hash', 'salt', { c: 5, dkLen: 32 });
  const sha512Key = pbkdf2(sha512, 'multi-hash', 'salt', { c: 5, dkLen: 64 });

  assert.strictEqual(sha256Key.length, 32);
  assert.strictEqual(sha512Key.length, 64);
  assert.notStrictEqual(bytesToHex(sha256Key), bytesToHex(sha512Key.subarray(0, 32)), 'different hashes must produce distinct keys');

  // Verify verification helper
  assert.strictEqual(verifyDerivedKey(sha256, 'multi-hash', 'salt', sha256Key, { c: 5 }), true);
  assert.strictEqual(verifyDerivedKey(sha256, 'wrong-pass', 'salt', sha256Key, { c: 5 }), false);
}

// Contract Assertion 6:
// pbkdf2 validates options throwing descriptive errors when iteration count or dkLen is less than 1
{
  // Iterations c < 1
  assert.throws(
    () => pbkdf2(sha256, 'password', 'salt', { c: 0 }),
    (err) => err instanceof Error && /"c" \(iterations\) must be >= 1/.test(err.message),
    'must throw when c < 1'
  );

  // dkLen < 1
  assert.throws(
    () => pbkdf2(sha256, 'password', 'salt', { c: 1, dkLen: 0 }),
    (err) => err instanceof Error && /"dkLen" must be >= 1/.test(err.message),
    'must throw when dkLen < 1'
  );

  // Non-number c
  assert.throws(
    () => pbkdf2(sha256, 'password', 'salt', { c: 'invalid' }),
    (err) => err instanceof Error,
    'must throw when c is not a number'
  );
}

console.log('All 6 contract assertions passed successfully.');

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

аноним