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 ... >
广告