CodeSampleX

示例

@noble/hashes 2.3.0: pbkdf2Async

已验证示例 — npm @noble/hashes 2.3.0: pbkdf2Async. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: pbkdf2Async is exported as an async function from…

sha256:dd364686eb6dc5bf8632e36c5f652506db002bdacdc259d6c3036aefa4083618

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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.pbkdf2Async in pkg:npm/%40noble/hashes@2.3.0
包
符号
  • @noble/hashes.pbkdf2Async
环境
node 22.23.2
创建时间
2026-09-06T23:51:56Z

契约

  1. pbkdf2Async is exported as an async function from @noble/hashes/pbkdf2.js returning a Promise
  2. pbkdf2Async derives RFC 6070 HMAC-SHA256 test vectors for string and Uint8Array inputs
  3. pbkdf2Async derives identical cryptographic keys across configurable work factors and asyncTick settings
  4. pbkdf2Async defaults to 32-byte derived key length and supports custom output sizes via dkLen
  5. pbkdf2Async supports different hash functions including sha256 and sha512
  6. pbkdf2Async 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.pbkdf2Async 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.pbkdf2Async

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

/**
 * Asynchronously derives a cryptographic key using PBKDF2.
 *
 * @param {import('@noble/hashes/utils.js').CHash} hash - PRF hash function (e.g., sha256, sha512)
 * @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>} Promise resolving to the derived key bytes
 */
export async function deriveKeyAsync(hash, password, salt, options) {
  return pbkdf2Async(hash, password, salt, options);
}

/**
 * Asynchronously derives a cryptographic key using PBKDF2 and formats as hexadecimal string.
 *
 * @param {import('@noble/hashes/utils.js').CHash} hash - PRF hash function
 * @param {string | Uint8Array} password - Password input
 * @param {string | Uint8Array} salt - Cryptographic salt
 * @param {{ c: number, dkLen?: number, asyncTick?: number }} options - PBKDF2 options
 * @returns {Promise<string>} Promise resolving to the derived key as hex string
 */
export async function deriveKeyHexAsync(hash, password, salt, options) {
  const bytes = await pbkdf2Async(hash, password, salt, options);
  return bytesToHex(bytes);
}

/**
 * Asynchronously verifies if a password and salt match an expected derived key using constant-time comparison.
 *
 * @param {import('@noble/hashes/utils.js').CHash} hash - PRF hash function
 * @param {string | Uint8Array} password - Password input
 * @param {string | Uint8Array} salt - Cryptographic salt
 * @param {Uint8Array} expectedKey - Expected derived key bytes
 * @param {{ c: number, dkLen?: number, asyncTick?: number }} options - PBKDF2 options
 * @returns {Promise<boolean>} Promise resolving to true if key matches
 */
export async function verifyKeyAsync(hash, password, salt, expectedKey, options) {
  const derived = await pbkdf2Async(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 { pbkdf2Async, sha256, sha512 };
test/contract.mjs
import assert from 'node:assert';
import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
import {
  deriveKeyAsync,
  deriveKeyHexAsync,
  verifyKeyAsync,
} from '../src/index.mjs';

// Contract Assertion 1:
// pbkdf2Async is exported as an async function from @noble/hashes/pbkdf2.js returning a Promise
{
  assert.strictEqual(typeof pbkdf2Async, 'function', 'pbkdf2Async must be a function');
  assert.strictEqual(typeof deriveKeyAsync, 'function', 'deriveKeyAsync helper must be a function');
  assert.strictEqual(typeof deriveKeyHexAsync, 'function', 'deriveKeyHexAsync helper must be a function');
  assert.strictEqual(typeof verifyKeyAsync, 'function', 'verifyKeyAsync helper must be a function');

  const pending = pbkdf2Async(sha256, 'test', 'test', { c: 1, dkLen: 32 });
  assert.strictEqual(typeof pending?.then, 'function', 'pbkdf2Async invocation must return a thenable Promise');
  const resolved = await pending;
  assert.strictEqual(resolved instanceof Uint8Array, true, 'resolved promise must be Uint8Array');
}

// Contract Assertion 2:
// pbkdf2Async derives RFC 6070 HMAC-SHA256 test vectors for string and Uint8Array inputs
{
  // RFC 6070 test vector 1: c = 1, dkLen = 32
  const key1 = await pbkdf2Async(sha256, 'password', 'salt', { c: 1, dkLen: 32 });
  assert.strictEqual(key1 instanceof Uint8Array, true, 'key1 must be a Uint8Array');
  assert.strictEqual(key1.length, 32, 'key1 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 = await pbkdf2Async(sha256, 'password', 'salt', { c: 2, dkLen: 32 });
  assert.strictEqual(
    bytesToHex(key2),
    'ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43',
    'RFC 6070 vector 2 digest mismatch'
  );

  // Verify helper deriveKeyAsync & deriveKeyHexAsync
  const key1Helper = await deriveKeyAsync(sha256, 'password', 'salt', { c: 1, dkLen: 32 });
  assert.deepStrictEqual(key1Helper, key1, 'deriveKeyAsync output must match pbkdf2Async');
  const key1Hex = await deriveKeyHexAsync(sha256, 'password', 'salt', { c: 1, dkLen: 32 });
  assert.strictEqual(key1Hex, '120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b');

  // Binary Uint8Array inputs
  const passwordBytes = utf8ToBytes('password');
  const saltBytes = utf8ToBytes('salt');
  const keyFromBytes = await pbkdf2Async(sha256, passwordBytes, saltBytes, { c: 2, dkLen: 32 });
  assert.deepStrictEqual(keyFromBytes, key2, 'Uint8Array inputs must match string inputs');

  // Multibyte Unicode inputs
  const utf8Password = 'p@sswørd🔑';
  const utf8Salt = 's@lt🧂';
  const keyUtf8Str = await pbkdf2Async(sha256, utf8Password, utf8Salt, { c: 5, dkLen: 32 });
  const keyUtf8Bytes = await pbkdf2Async(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 across configurable work factors and asyncTick settings
{
  const cValues = [1, 2, 10, 50];
  for (const c of cValues) {
    const keyStandard = await pbkdf2Async(sha256, 'async-password', 'async-salt', { c, dkLen: 32 });
    assert.strictEqual(keyStandard.length, 32);

    // Test with various asyncTick yield intervals
    const keyWithTick1 = await pbkdf2Async(sha256, 'async-password', 'async-salt', {
      c,
      dkLen: 32,
      asyncTick: 1,
    });
    assert.deepStrictEqual(keyWithTick1, keyStandard, `asyncTick 1 must match for c=${c}`);

    const keyWithTick10 = await pbkdf2Async(sha256, 'async-password', 'async-salt', {
      c,
      dkLen: 32,
      asyncTick: 10,
    });
    assert.deepStrictEqual(keyWithTick10, keyStandard, `asyncTick 10 must match for c=${c}`);
  }

  // Concurrent asynchronous derivations
  const [resA, resB] = await Promise.all([
    pbkdf2Async(sha256, 'passA', 'saltA', { c: 5, dkLen: 32 }),
    pbkdf2Async(sha256, 'passB', 'saltB', { c: 5, dkLen: 32 }),
  ]);
  assert.notDeepStrictEqual(resA, resB, 'concurrent derivations with distinct inputs must not collide');
}

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

  // Custom shorter dkLen (16 bytes)
  const shortKey = await pbkdf2Async(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 longer dkLen (64 bytes spanning multiple PRF blocks)
  const longKey = await pbkdf2Async(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:
// pbkdf2Async supports different hash functions including sha256 and sha512
{
  const sha256Key = await pbkdf2Async(sha256, 'multi-hash', 'salt', { c: 5, dkLen: 32 });
  const sha512Key = await pbkdf2Async(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 verifyKeyAsync helper
  const valid = await verifyKeyAsync(sha256, 'multi-hash', 'salt', sha256Key, { c: 5 });
  assert.strictEqual(valid, true, 'verifyKeyAsync must return true for matching key');
  const invalid = await verifyKeyAsync(sha256, 'wrong-pwd', 'salt', sha256Key, { c: 5 });
  assert.strictEqual(invalid, false, 'verifyKeyAsync must return false for mismatching key');
}

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

  // dkLen < 1
  await assert.rejects(
    async () => pbkdf2Async(sha256, 'password', 'salt', { c: 1, dkLen: 0 }),
    (err) => err instanceof Error && /"dkLen" must be >= 1/.test(err.message),
    'must reject when dkLen < 1'
  );

  // Non-number c
  await assert.rejects(
    async () => pbkdf2Async(sha256, 'password', 'salt', { c: 'invalid' }),
    (err) => err instanceof Error,
    'must reject when c is not a number'
  );
}

console.log('All @noble/hashes.pbkdf2Async contract assertions passed successfully.');

原始种子者

匿名