Node.js 中的 crypto.getDiffieHellman() 方法
crypto.createDiffieHellmanGroup() 用于创建预定的 DiffieHellmanGroup 密钥交换对象。一些受支持的 DiffieHellmanGroup 有:modp1、modp2、modp5、modp 14、modp16、modp17 等。使用此方法的好处是当事方不需要生成或交换组模数,从而节省了处理时间。
语法
crypto.getDiffieHelmmanGroup(groupName)
参数
以上参数的说明如下 −
groupName – 接受组名的输入。输入类型为“string”。
示例
使用名称创建文件 - getdiffieHellman.js 并复制下面的代码片段。创建文件后,使用以下命令运行此代码,如下面的示例中所示 −
node getDiffieHellman.js
getdiffieHellman.js
// crypto.getDiffieHellman() Demo Example
// Importing the crypto module
const crypto = require('crypto');
const server = crypto.getDiffieHellman('modp1');
const client = crypto.getDiffieHellman('modp1');
// Printing DiffieHellman values
console.log(server);
console.log(client);
// Generating public and private keys
server.generateKeys();
client.generateKeys();
// Gettong public key
const serverSecret = server.computeSecret(client.getPublicKey(), null, 'hex');
const clientSecret = client.computeSecret(server.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(serverSecret === clientSecret);输出
C:\home
ode>> node getDiffieHellman.js DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 } DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 } true
示例
我们来看另一个示例。
// crypto.getDiffieHellman() Demo Example
// Importing the crypto module
const crypto = require('crypto');
const dh1 = crypto.getDiffieHellman('modp17');
const dh2 = crypto.getDiffieHellman('modp14');
// Generating public and private keys
dh1.generateKeys();
dh2.generateKeys();
// Gettong public key
const dh1Key = dh1.computeSecret(dh2.getPublicKey(), null, 'hex');
const dh2Key = dh2.computeSecret(dh1.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(dh1Key === dh2Key);输出
C:\home
ode>> node getDiffieHellman.js internal/crypto/diffiehellman.js:102 const ret = this._handle.computeSecret(toBuf(key, inEnc)); ^ Error: Supplied key is too large at DiffieHellmanGroup.dhComputeSecret [as computeSecret] (internal/crypto/diffiehellman.js:102:28) at Object.<anonymous> (/home/node/test/getDiffieHellman .js:15:20) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP