diffieHellman.getPublicKey() 方法是加密模塊中 DiffieHellman 類的內置應用程序編程接口,用於返回 dh 對象的公鑰。
用法:
diffieHellman.getPublicKey([encoding])
參數:該方法將編碼作為參數。
返回值:它返回 diffieHellman 公鑰。如果指定了編碼,則返回一個字符串,否則返回一個緩衝區。
範例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 index.js
輸出:
Public Key ( with encoding ): m/tuBRWr1mHOT4VzjRvcgZ+9Vtp925GS78Mdu E7DfTxAm5750700EbWzVgLZWZ8N0AQoN1xQLlgDtBsdDo1wnQ== Public Key ( without encoding ): <Buffer 9b fb 6e 05 15 ab d6 61 ce 4f 85 73 8d 1b dc 81 9f bd 56 da 7d db 91 92 ef c3 1d b8 4e c3 7d 3c 40 9b 9e f9 d3 bd 34 11 b5 b3 56 02 d9 59 9f 0d d0 04 ... >
範例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
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js x509.toLegacyObject()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
注:本文由純淨天空篩選整理自braktim99大神的英文原創作品 Node.js diffieHellman.getPublicKey() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。