diffieHellman.generateKeys() 方法是加密模塊中 DiffieHellman 類的內置應用程序編程接口,用於生成 DiffieHellman (dh) 對象的私鑰和公鑰值。
用法:
diffieHellman.generateKeys([encoding])
參數:該方法將編碼作為參數。
返回值:返回指定編碼的 DiffieHellman 公鑰。如果未提供編碼,則返回緩衝區,否則返回字符串。
範例1:
index.js
// Node.js program to demonstrate the
// diffieHellman.generateKeys() method
// Destructure createDiffieHellman method from crypto
const { createDiffieHellman } = require('crypto');
// Instances of the DiffieHellman class
const dh = createDiffieHellman(512);
// Generate DH's Key
// No encoding specified
// Return Buffer
let dhKey = dh.generateKeys()
console.log('\nIs Buffer return ( encoding not specified ):' +
Buffer.isBuffer( dhKey ) ) // true
console.log('Return value:')
console.log( dhKey )
// Encoding specified
// Return String
dhKey = dh.generateKeys('base64')
console.log('\nIs Buffer return ( encoding specified ):' +
Buffer.isBuffer( dhKey ) ) // true
console.log('Return value:')
console.log( dhKey )
使用以下命令運行index.js文件:
node index.js
輸出:
Is Buffer return ( encoding not specified ):true Return value: <Buffer 6d 17 8c ea 74 27 5b f4 86 f8 72 f9 73 93 19 8b 27 90 86 e7 d8 1b 1c 50 b2 65 9a 66 bc 2c 4d 49 f6 46 3e b5 1c 09 e5 ef 5c b9 8e fc 65 95 aa 40 3a 6c ... 14 more bytes> Is Buffer return ( encoding specified ):false Return value: bReM6nQnW/SG+HL5c5MZiyeQhufYGxxQsmWaZrwsTUn2Rj61HAnl71y5jvxllapAO mwITlF8/1Z67Nt7Lc8tqA==
範例2:
index.js
// Node.js program to demonstrate the
// diffieHellman.generateKeys() method
// Destructure createDiffieHellman method from crypto
const { createDiffieHellman } = require('crypto');
// Generate Alice's keys...
const alice = createDiffieHellman(512);
// Generate Alices's Prime
const alicePrime = alice.getPrime();
// Generate Alice's Generator
const aliceGenerator = alice.getGenerator()
// Generate Alice's Key
const aliceKey = alice.generateKeys('base64');
// Generate Bob's keys...
const bob = createDiffieHellman( alicePrime, aliceGenerator );
// Generate Bobs's Prime
const bobPrime = bob.getPrime();
// Generate Bob's Generator
const bobGenerator = bob.getGenerator()
// Generate Bob's Key
const bobKey = bob.generateKeys('base64');
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey, 'base64', 'base64');
const bobSecret = bob.computeSecret(aliceKey, 'base64', 'base64');
let isSymmetric = aliceSecret == bobSecret
// true
console.log( `Is Symmetric key generation successful:${ isSymmetric }` );
使用以下命令運行index.js文件:
node index.js
輸出:
Is Symmetric key generation successful:true
參考: https://nodejs.org/api/crypto.html#crypto_diffiehellman_generatekeys_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.generateKeys() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。