Node.js – diffieHellman.getGenerator() 方法
diffieHellman.getGenerator() 方法以指定编码返回 Diffie-Hellman 生成器。如果传递了编码,则返回一个字符串,否则会返回一个缓冲区。
语法
diffieHellman.getGenerator([encoding])
参数
encoding - 此参数指定返回值的编码。
示例 1
创建一个名为 "generator.js" 的文件并复制以下代码。创建文件后,使用命令 "node generator.js" 运行此代码,如下例所示
// diffieHellman.getPrime() Demo Example // Importing cryptoDiffieHellman from the crypto module const { createDiffieHellman } = require('crypto'); // Initializing the diffieHellman object const dh = createDiffieHellman(512); // Generate DiffieHellman's Generator // Defining generator let dhGenerator = dh.getGenerator() console.log('Buffer (when encoding is not specified) : ', dhGenerator) // Encoding specified // Return String dhGenerator = dh.getGenerator('base64') console.log('String (when encoding is specified) : ', dhGenerator)
输出
Buffer (when encoding is not specified) : <Buffer 02> String (when encoding is specified) : Ag==
示例 2
让我们看一个示例。
// diffieHellman.getGenerator() 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 }')
输出
Are keys Symmetric : ${ isSymmetric }
广告