Node.js – diffieHellman.getPublicKey() 方法
diffieHellman.getPublicKey() 返回由指定的编码指定的 Diffie-Hellman 生成的公钥。如果传递了编码,它将返回一个字符串,否则它将返回一个缓冲区。
语法
diffieHellman.getPublicKey([encoding])
参数
编码 – 此参数指定返回值的编码。
示例 1
创建一个名为 “publicKey.js” 的文件,并复制以下代码片段。创建文件后,使用命令 “node publicKey.js” 运行此代码。
// diffieHellman.getPublicKey() Demo Example // Importing the crypto module const crypto = require('crypto') // Initializing the diffieHellman const dh = crypto.createDiffieHellman(512); // Taking default publicKey as null let publicKey = null // Generate Keys dh.generateKeys() // Getting string with base64 encoding publicKey = dh.getPublicKey('base64') console.log('Public Key (with base64 encoding): ', publicKey, '
') // Getting buffer without encoding publicKey = dh.getPublicKey() console.log('Public Key ( ithout encoding): ', publicKey, '
')
输出
Public Key (with base64 encoding): ZY0wKH6d7Te8OPeIgHr7OlwSiH8d7MLGya9wopMgt5/liiKwFTgXsGE/07BQ6u98kUJJbr8cRgtD02D2I21xsg== Public Key ( ithout encoding): <Buffer 65 8d 30 28 7e 9d ed 37 bc 38 f7 88 80 7a fb 3a 5c 12 88 7f 1d ec c2 c6 c9 af 70 a2 93 20 b7 9f e5 8a 22 b0 15 38 17 b0 61 3f d3 b0 50 ea ef 7c 91 42 ... >
示例 2
让我们看另一个示例。
// diffieHellman.getPublicKey() Demo Example // Importing the crypto module const crypto = require('crypto') // Initializing the diffieHellman const a = crypto.createDiffieHellman(512); const b = crypto.createDiffieHellman( a.getPrime(), a.getGenerator() ); // Generating Keys a.generateKeys() b.generateKeys() // Generating public key for a let keyA = a.getPublicKey('base64') // Generating public key for b let keyB = b.getPublicKey('base64') // Computing secret let secretA = a.computeSecret(keyB, 'base64', 'base64') let secretB = b.computeSecret(keyA, 'base64', 'base64') if(secretA === secretB) console.log('Symmetric key A:', secretA) console.log('Symmetric key B:', secretB)
输出
Symmetric key A: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA== Symmetric key B: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA==
广告