📜  Node.js diffieHellman.getPublicKey() 方法

📅  最后修改于: 2022-05-13 01:56:37.729000             🧑  作者: Mango

Node.js diffieHellman.getPublicKey() 方法

diffieHellman.getPublicKey()方法是加密模块中DiffieHellman类的内置应用程序编程接口,用于返回dh对象的公钥

句法:

diffieHellman.getPublicKey([encoding])

参数:此方法将编码作为参数。

返回值:它返回 diffieHellman 公钥。如果指定了编码,则返回一个字符串,否则返回一个 Buffer。

示例 1:

index.js
// Node.js program to demonstrate the
// diffieHellman.getPublicKey() Method
  
const crypto = require('crypto')
// Instance of  diffieHellman class
const dh = crypto.createDiffieHellman(512);
let publicKey = null
  
// Generate Keys
dh.generateKeys()
  
// Pass 'base64' as encoding, return String
publicKey = dh.getPublicKey('base64')
console.log('Public Key ( with encoding ): ', publicKey, '\n')
  
// Without encoding, return Buffer
publicKey = dh.getPublicKey()
console.log('Public Key ( without encoding ): ', publicKey, '\n')


index.js
// Node.js program to demonstrate the
// diffieHellman.getPublicKey() Method
  
const crypto = require('crypto')
  
// Instances of diffieHellman class
const alice = crypto.createDiffieHellman(512);
const bob = crypto.createDiffieHellman( 
    alice.getPrime(), alice.getGenerator() );
  
// Generate Keys
alice.generateKeys()
bob.generateKeys()
  
// Alice's publicKey
let aliceKey = alice.getPublicKey('base64')
  
// Bob's publicKey 
let bobKey = bob.getPublicKey('base64')
  
// Compute secret
let aliceSecret = alice.computeSecret(bobKey, 'base64', 'base64')
let bobSecret = bob.computeSecret(aliceKey, 'base64', 'base64')
  
if( aliceSecret === bobSecret )
    console.log('Symmetric key :', aliceSecret)


运行index.js 文件 使用以下命令:

node index.js

输出:

Public Key ( with encoding ):  m/tuBRWr1mHOT4VzjRvcgZ+9Vtp925GS78Mdu
E7DfTxAm5750700EbWzVgLZWZ8N0AQoN1xQLlgDtBsdDo1wnQ== 

Public Key ( without encoding ):  

示例 2:

index.js

// Node.js program to demonstrate the
// diffieHellman.getPublicKey() Method
  
const crypto = require('crypto')
  
// Instances of diffieHellman class
const alice = crypto.createDiffieHellman(512);
const bob = crypto.createDiffieHellman( 
    alice.getPrime(), alice.getGenerator() );
  
// Generate Keys
alice.generateKeys()
bob.generateKeys()
  
// Alice's publicKey
let aliceKey = alice.getPublicKey('base64')
  
// Bob's publicKey 
let bobKey = bob.getPublicKey('base64')
  
// Compute secret
let aliceSecret = alice.computeSecret(bobKey, 'base64', 'base64')
let bobSecret = bob.computeSecret(aliceKey, 'base64', 'base64')
  
if( aliceSecret === bobSecret )
    console.log('Symmetric key :', aliceSecret)

运行index.js 文件 使用以下命令:

node index.js

输出:

Symmetric key : VyeZOZm+hZQtZVp6HQdhWTkrHfZb8tR/yRiD99ljFWsnVHJNULdjnc
5oN5/mMSNqEWFqiJ0U14JYngJwXL008A==

参考: https://nodejs.org/api/crypto.html#crypto_diffiehellman_getpublickey_encoding