实现说明
唯一的导入来源是 node:crypto(Node.js 内建),暴露出 createHash、diffieHellman、generateKeyPairSync。
各个操作都建立在顶层绑定之上:alice、bob、fromAlice、fromBob。
使用要点
node:crypto是 Node.js 内建模块——随运行时自带,无需安装。- 演示输出是带标签的(
same shared bytes:、shared bits:、key length:),每个操作都会留下自己的一行标注。
常见问题
需要安装第三方包吗?
不需要——node:crypto 是 Node.js 内建模块,无需安装。
核心语句
const fromAlice = diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
const fromBob = diffieHellman({ privateKey: bob.privateKey, publicKey: alice.publicKey });
const sessionKey = createHash('sha256').update(fromAlice).digest('hex');
代码示例
import { createHash, diffieHellman, generateKeyPairSync } from 'node:crypto';
// generateKeyPairSync creates an ECDH-capable key pair on the P-256 curve
const alice = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const bob = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
// Each side derives bits from the other's public key with its own private key
const fromAlice = diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
const fromBob = diffieHellman({ privateKey: bob.privateKey, publicKey: alice.publicKey });
console.log('same shared bytes:', fromAlice.equals(fromBob));
console.log('shared bits:', fromAlice.length * 8);
// Hash the raw secret into a symmetric key for AES
const sessionKey = createHash('sha256').update(fromAlice).digest('hex');
console.log('key length:', sessionKey.length, 'hex chars');