Node.js - diffieHellman.setPublicKey() 方法
diffieHellman.setPublicKey() 设置 Diffie-Hellman 生成的公钥。如果提供了 encoding 参数,私钥将是一个字符串。如果未提供编码,privateKey 将为 buffer、TypedArray 或 DataView 类型。
语法
diffieHellman.setPublicKey( publicKey, [encoding] )
其中,encoding 是指定公钥编码的参数。
示例 1
创建一个名为 "publicKey.js" 的文件,并将以下代码段复制到其中。创建文件后,使用命令 "node publicKey.js" 运行此代码,如下例所示 −
// diffieHellman.setPublicKey() 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, publicKey){
// Initializing diffieHellman
const dh = crypto.createDiffieHellman(512)
// Setting the publicKey key
dh.setPublicKey(publicKey)
if( publicKey.equals(dh.getPublicKey()) )
console.log(publicKey)
console.log("DH publicKey is set successfully")
}输出
C:\home
ode>> node publicKey.js <Buffer 30 82 01 5f 02 01 00 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 04 82 01 49 30 82 01 45 02 01 00 02 43 02 e0 2c ab 4d f9 8a ab 2e 37 92 df 01 a5 b4 ... > DH publicKey is set successfully
示例 2
我们来看另一个示例 −
// diffieHellman.setPublicKey() 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, publicKey){
// Encoding the key in base64
publicKey = publicKey.toString('base64');
// Initializing diffieHellman
const dh = crypto.createDiffieHellman( 512 )
// Setting the diffieHellman's privateKey
dh.setPublicKey( publicKey, 'base64' )
// Checking equality between both keys
if( publicKey === dh.getPublicKey('base64') )
console.log(publicKey)
console.log( "Successfully assigned the public key" )
}输出
C:\home
ode>> node publicKey.js MIHnAgEAMIHABgcqhkjOOAQBMIG0AkkAnTspVsa5ck4xDnt4/xVGdIPXfOSTyePfGDliGbZLLErNQWVfykNc7fIMetCo6AeKVJyGNT+d3U6fFp+/HRXxXvqdITB39NcRAh0A72mnUzdgBxgjV+eYTYSVGuSjdClMli0CEiLyjQJIHZpvRyoeYvrb4A74pkMSoV51KBF4zi/667ypv3UZ0H9w0sXuy5SXuW1/0ngQWkrTECZayH/HahOWwwxQGCSX6a7bcAtgQ4QVBB8CHQC4Vqyod315EH6fsJykRzF+y6o3oAQc5Pf7Pu6l Successfully assigned the public key
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP