Node.js – diffieHellman.getPrime() 方法


diffieHellman.getPrime() 返回使用指定編碼生成的 Diffie-Hellman 質數。如果傳遞了編碼,則返回字串;否則,會返回緩衝區。

語法

diffieHellman.getPrime([encoding])

引數

它僅需一個引數

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

示例 1

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

// diffieHellman.getPrime() Demo Example

// Importing cryptoDiffieHellman from the crypto module
const { createDiffieHellman } = require('crypto');

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

// Generating prime from diffieHellman
let dhPrime = dh.getPrime()
console.log('Buffer (when encoding is not specified): ', dhPrime)

// Generating prime with specified encoding
dhPrime = dh.getPrime('base64')
console.log('String (when encoding is specified): ', dhPrime)

輸出

Buffer (when encoding is not specified): <Buffer bd b7 17 22 2f 08 fa 82 2e b6 7d 5c 7d 25 5c 3e 17 9f 47 59 8d 67 eb 87 42 9d 86 c2 a7 85 3b 77 90 f2 e0 b9 70 8a b5 d6 9e 47 13 4c 7b ef 3e df 71 a9 ... >
String (when encoding is specified): vbcXIi8I+oIutn1cfSVcPhefR1mNZ+uHQp2GwqeFO3eQ8uC5cIq11p5HE0x77z7fcanQvU7p58u1yKv9fa3Muw==

示例 2

我們來看另一個示例。

// diffieHellman.getPrime() Demo Example

// Importing cryptoDiffieHellman from the crypto module
const { createDiffieHellman } = require('crypto');

// Generating keys for 'a'
const a = createDiffieHellman(512);

// Generating prime for 'a'
const primeA = a.getPrime();

// Generating a's generator
const generatorA = a.getGenerator()

// Generating a's generatorKeys
const keyA = a.generateKeys();

// Generating keys for b
const b = createDiffieHellman( primeA, generatorA );

// Generating prime for b
const primeB = b.getPrime();

// Generating b's generator
const generatorB = b.getGenerator()

// Generating b's generatorKeys
const keyB = b.generateKeys();

// Exchanging the secret
const secretA = a.computeSecret(keyB);
const secretB = b.computeSecret(keyA);

let isSymmetric =
   secretA.toString('hex') == secretB.toString('hex')

console.log( `Are keys Symmetric : ${ isSymmetric }` )
console.log("Symmetric keyA: ", secretA)
console.log("Symmetric keyB: ", secretB)

輸出

Are keys Symmetric : true
Symmetric keyA: <Buffer 6a ba e7 5c b2 7a d2 b3 eb 67 ad 6e 2d 35 04 e4 cc fc a8 25 4e 03 f9 68 98 dd f6 83 53 75 5b f6 6b b3 2f 2f 09 a3 24 96 83 45 57 d5 3f 8c b2 60 ba 18 ... >
Symmetric keyB: <Buffer 6a ba e7 5c b2 7a d2 b3 eb 67 ad 6e 2d 35 04 e4 cc fc a8 25 4e 03 f9 68 98 dd f6 83 53 75 5b f6 6b b3 2f 2f 09 a3 24 96 83 45 57 d5 3f 8c b2 60 ba 18 ... >

更新於: 29-10-2021

78 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.