Node.js - diffieHellman.setPublicKey() 方法


diffieHellman.setPublicKey() 設定 Diffie-Hellman 生成的公鑰。如果提供了 encoding 引數,私鑰將是一個字串。如果未提供編碼,privateKey 將為 bufferTypedArrayDataView 型別。

語法

diffieHellman.setPublicKey( publicKey, [encoding] )

其中,encoding 是指定公鑰編碼的引數。

示例 1

建立一個名為 "publicKey.js" 的檔案,並將以下程式碼段複製到其中。建立檔案後,使用命令 "node publicKey.js" 執行此程式碼,如下例所示 −

// diffieHellman.setPublicKey() Demo Example

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

// Generating the key pairs(public & private)
crypto.generateKeyPair('rsa',
   {
      modulusLength: 530,
      primeLength: 512,
      publicKeyEncoding: {
         type: 'spki',
         format: 'der'
      },
   privateKeyEncoding: {
      type: 'pkcs8',
      format: 'der'
   }
},
createDiffieHellman
)

function createDiffieHellman(err, publicKey, publicKey){
   // Initializing diffieHellman
   const dh = crypto.createDiffieHellman(512)
   // Setting the publicKey key
   dh.setPublicKey(publicKey)

   if( publicKey.equals(dh.getPublicKey()) )
      console.log(publicKey)
      console.log("DH publicKey is set successfully")
}

輸出

C:\home
ode>> node publicKey.js <Buffer 30 82 01 5f 02 01 00 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 04 82 01 49 30 82 01 45 02 01 00 02 43 02 e0 2c ab 4d f9 8a ab 2e 37 92 df 01 a5 b4 ... > DH publicKey is set successfully

示例 2

我們來看另一個示例 −

// diffieHellman.setPublicKey() Demo Example

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

// Generating the key pairs(public & private)
crypto.generateKeyPair('dsa',
   {
      modulusLength: 530,
      primeLength: 512,
      publicKeyEncoding: {
         type: 'spki',
         format: 'der'
      },
      privateKeyEncoding: {
         type: 'pkcs8',
         format: 'der'
      }
   },
   createDiffieHellman
)

function createDiffieHellman(err, publicKey, publicKey){
   // Encoding the key in base64
   publicKey = publicKey.toString('base64');
   // Initializing diffieHellman
   const dh = crypto.createDiffieHellman( 512 )
   // Setting the diffieHellman's privateKey
   dh.setPublicKey( publicKey, 'base64' )

   // Checking equality between both keys
   if( publicKey === dh.getPublicKey('base64') )
      console.log(publicKey)
      console.log( "Successfully assigned the public key" )
}

輸出

C:\home
ode>> node publicKey.js MIHnAgEAMIHABgcqhkjOOAQBMIG0AkkAnTspVsa5ck4xDnt4/xVGdIPXfOSTyePfGDliGbZLLErNQWVfykNc7fIMetCo6AeKVJyGNT+d3U6fFp+/HRXxXvqdITB39NcRAh0A72mnUzdgBxgjV+eYTYSVGuSjdClMli0CEiLyjQJIHZpvRyoeYvrb4A74pkMSoV51KBF4zi/667ypv3UZ0H9w0sXuy5SXuW1/0ngQWkrTECZayH/HahOWwwxQGCSX6a7bcAtgQ4QVBB8CHQC4Vqyod315EH6fsJykRzF+y6o3oAQc5Pf7Pu6l Successfully assigned the public key

更新於: 2022-01-17

96 次瀏覽量

開啟你的 職業生涯

透過完成課程來獲得認證

開始學習
廣告