Node.js – diffieHellman.getPublicKey() 方法


diffieHellman.getPublicKey() 返回由指定的編碼指定的 Diffie-Hellman 生成的公鑰。如果傳遞了編碼,它將返回一個字串,否則它將返回一個緩衝區。

語法

diffieHellman.getPublicKey([encoding])

引數

  • 編碼 – 此引數指定返回值的編碼。

示例 1

建立一個名為 “publicKey.js” 的檔案,並複製以下程式碼片段。建立檔案後,使用命令 “node publicKey.js” 執行此程式碼。

// diffieHellman.getPublicKey() Demo Example

// Importing the crypto module
const crypto = require('crypto')

// Initializing the diffieHellman
const dh = crypto.createDiffieHellman(512);

// Taking default publicKey as null
let publicKey = null

// Generate Keys
dh.generateKeys()

// Getting string with base64 encoding
publicKey = dh.getPublicKey('base64')
console.log('Public Key (with base64 encoding): ', publicKey, '
') // Getting buffer without encoding publicKey = dh.getPublicKey() console.log('Public Key ( ithout encoding): ', publicKey, '
')

輸出

Public Key (with base64 encoding): ZY0wKH6d7Te8OPeIgHr7OlwSiH8d7MLGya9wopMgt5/liiKwFTgXsGE/07BQ6u98kUJJbr8cRgtD02D2I21xsg==

Public Key ( ithout encoding): <Buffer 65 8d 30 28 7e 9d ed 37 bc 38 f7 88 80 7a fb 3a 5c 12 88 7f 1d ec c2 c6 c9 af 70 a2 93 20 b7 9f e5 8a 22 b0 15 38 17 b0 61 3f d3 b0 50 ea ef 7c 91 42 ... >

示例 2

讓我們看另一個示例。

// diffieHellman.getPublicKey() Demo Example

// Importing the crypto module
const crypto = require('crypto')

// Initializing the diffieHellman
const a = crypto.createDiffieHellman(512);
const b = crypto.createDiffieHellman(
   a.getPrime(), a.getGenerator() );

// Generating Keys
a.generateKeys()
b.generateKeys()

// Generating public key for a
let keyA = a.getPublicKey('base64')

// Generating public key for b
let keyB = b.getPublicKey('base64')

// Computing secret
let secretA = a.computeSecret(keyB, 'base64', 'base64')
let secretB = b.computeSecret(keyA, 'base64', 'base64')

if(secretA === secretB)
   console.log('Symmetric key A:', secretA)
   console.log('Symmetric key B:', secretB)

輸出

Symmetric key A: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA==
Symmetric key B: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA==

時間更新: 29-Oct-2021

242 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告