← 中文资源

简体中文版本

diffieHellman 推导 ECDH 共享密钥

两把 P-256 ECDH 密钥各自用自己的私钥与对方公钥做 diffieHellman 推导,得到的共享字节完全一致,再经 SHA-256 哈希成 AES 会话密钥,密钥协商不再手写大数运算。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

same shared bytes: true
shared bits: 256
key length: 64 hex chars

实现说明

唯一的导入来源是 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');