Node.js – diffieHellman.setPrivateKey() 方法
该组生成的的Diffie-Hellman私钥。如果提供了编码参数,则私钥将是一个字符串。如果未提供编码,则私钥将是缓冲区类型。diffieHellman.setPrivateKey()
语法
diffieHellman.setPrivateKey( privateKey, [encoding] )
参数
encoding-此参数指定私钥的编码。
示例1
创建一个名为“privateKey.js”的文件并复制以下代码。创建文件后,使用命令“nodeprivateKey.js”运行此代码,如下例所示
//diffieHellman.setPrivateKey()演示示例 //导入加密模块 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){ //初始化diffieHellman const dh = crypto.createDiffieHellman(512) //设置私钥 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()演示示例 //导入加密模块 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){ //以base64编码密钥 privateKey = privateKey.toString('base64'); //初始化diffieHellman const dh = crypto.createDiffieHellman( 512 ) //设置diffieHellman的私钥 dh.setPrivateKey( privateKey, 'base64' ) //检查两个键之间的相等性 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