Node.js – diffieHellman.setPrivateKey()方法
diffieHellman.setPrivateKey()设置Diffie-Hellman生成的私钥。私钥在提供编码参数时为字符串。如果没有提供编码,则私钥的类型为缓冲区。
语法
diffieHellman.setPrivateKey( privateKey, [encoding] )
参数
编码 - 此参数指定私钥的编码方式。
示例1
创建一个名为“privateKey.js”的文件,并复制以下代码。创建文件后,使用命令“node privateKey.js”运行此代码,如下例所示
// diffieHellman.setPrivateKey() Demo Example // Importing the crypto module const crypto = require('crypto') // Generating the key pairs(public & private) crypto.generateKeyPair('rsa', { modulusLength: 530, primeLength: 512, publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }, createDiffieHellman ) function createDiffieHellman(err, publicKey, privateKey){ // Initializing diffieHellman const dh = crypto.createDiffieHellman(512) // Setting the private key dh.setPrivateKey(privateKey) if( privateKey.equals(dh.getPrivateKey()) ) console.log(privateKey) console.log("DH private Key is set successfully") }
输出
将产生以下输出 −
<Buffer 30 82 01 5e 02 01 00 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 04 82 01 48 30 82 01 44 02 01 00 02 43 03 07 b1 e8 13 90 8b 34 f2 d8 45 51 a6 85 1a ... > DH private Key is set successfully
示例2
我们来看另一个示例
// diffieHellman.setPrivateKey() Demo Example // Importing the crypto module const crypto = require('crypto') // Generating the key pairs(public & private) crypto.generateKeyPair('dsa', { modulusLength: 530, primeLength: 512, publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }, createDiffieHellman ) function createDiffieHellman(err, publicKey, privateKey){ // Encoding the key in base64 privateKey = privateKey.toString('base64'); // Initializing diffieHellman const dh = crypto.createDiffieHellman( 512 ) // Setting the diffieHellman's privateKey dh.setPrivateKey( privateKey, 'base64' ) // Checking equality between both keys if( privateKey === dh.getPrivateKey('base64') ) console.log(privateKey) console.log( "Successfully assigned the private key" ) }
输出
MIHmAgEAMIHABgcqhkjOOAQBMIG0AkkA96JCvzbJkAmHtKSKljhJIomU8rKKtr2LF IaCiy+/BA/WlTqqn1+HCE7sW5RcVY7eVnv58u+9YMewXEwFDEdc0Po8b30akc+DAh 0A7ZkC4ZTiYz2AZ/3tjr9Z6jrPxh0ZVW3iwT/xWQJIT43jCxqeif/fnnYpt4S2VoT 3K82U/sgKtyYdpvPag5eJLB9ELTHA5w2E2ol4DSlsNbTXC4zUsUoZKorULHq3bCoy ev1ewoVsBB4CHBcHJboiyIg1ysR+gq0QIq/E0eKIIhjj4+OfpZY= Successfully assigned the private key
广告