Node.js - diffieHellman.computeSecret() 方法
diffieHellman.computeSecret() 用於使用其他方的公鑰計算共享金鑰,並返回計算出的共享金鑰。suppliedKey 使用指定的 inputEncoding 進行解釋,而金鑰使用指定的 outputEncoding 進行編碼。如果未指定 inputEncoding,則其他 publicKey 預計是一個緩衝區,DataView。
語法
diffieHellman.computeSecret(otherPublicKey, [inputEncoding], [outputEncoding])
引數
otherPublicKey – 這是用於計算金鑰的公鑰。
inputEncoding – 此編碼用於解釋所提供的金鑰。
outputEncoding – 此編碼用於對計算出的機密值進行編碼。
示例 1
建立一個名為 "computeSecret.js" 的檔案,複製以下程式碼段。建立檔案後,使用命令 "node computSecret.js" 執行此程式碼,如下面的示例所示 −
// diffieHellman.computeSecret() Demo Example
// Importing the crypto module
const crypto = require('crypto')
// Creating diffieHellman instances
const a = crypto.createDiffieHellman('modp15');
const b = crypto.createDiffieHellman('modp15');
// Creating keys using base64
const keyA = a.generateKeys('base64');
// Creating key using hex
const keyB = b.generateKeys('hex');
// Creating secret using diffieHellman
const secretA = a.computeSecret(keyB, 'hex');
// Creating secret using diffieHellman
const secretB = b.computeSecret(keyA, 'base64');
// Checking if the resultant secrets are equal
const isSymmetric = secretA.equals(secretB)
if ( isSymmetric )
console.log('Symmetric key A: ', secretA)
console.log('Symmetric key B: ', secretB)
輸出
C:\home
ode>> node computeSecret.js Symmetric key A: <Buffer 43 4d aa ec dc c6> Symmetric key B: <Buffer 43 4d aa ec dc c6>
示例 2
我們來看一個例子 −
// diffieHellman.computeSecret() Demo Example
// Importing the crypto module
const crypto = require('crypto')
// Creating diffieHellman instances
const a = crypto.createDiffieHellman(512);
const b = crypto.createDiffieHellman(a.getPrime(), a.getGenerator());
// Creating keys using base64
const keyA = a.generateKeys('base64');
const keyB = b.generateKeys('base64');
// Creating secret using diffieHellman
const secretA = a.computeSecret(keyB, 'base64', 'hex');
const secretB = b.computeSecret(keyA, 'base64', 'hex');
// Checking if the resultant secrets are equal
if( secretA === secretB )
console.log(`Symmetric key A: ${ secretA }`)
console.log(`Symmetric key B: ${ secretB }`)輸出
C:\home
ode>> node computeSecret.js Symmetric key A: 44badc3e4ad43d7c887190104a63f0b68222678da1cae92b54a146c243f7b354061e958e59aebce43f72016123bd133d66135e3341ce47a18a1d7a07c86c8ddb Symmetric key B: 44badc3e4ad43d7c887190104a63f0b68222678da1cae92b54a146c243f7b354061e958e59aebce43f72016123bd133d66135e3341ce47a18a1d7a07c86c8ddb
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP