Node.js diffieHellman.setPublicKey() 方法
diffieHellman.setPublicKey() 方法是加密模块中 DiffieHellman 类(dh)的内置应用程序编程接口,用于设置 diffieHellman 对象的公钥。
语法:
diffieHellman.setPublicKey(publicKey[, encoding])
参数:
此方法接受以下两个参数:
- publicKey: 用于指示私钥。
- encoding: 用于指示publicKey的编码方式。如果提供了编码方式,publicKey应为字符串,否则为Buffer、TypedArray或DataView。
示例1:
index.js
// Node.js program to demonstrate the
// diffieHellman.setPublicKey() Method
const crypto = require('crypto')
crypto.generateKeyPair('dh',
{
primeLength: 512,
publicKeyEncoding: {
type: 'spki',
format: 'der'
},
publicKeyEncoding: {
type: 'pkcs8',
format: 'der'
}
},
cb
)
function cb(err, publicKey, publicKey) {
// Create Diffie-Hellman instance
const dh = crypto.createDiffieHellman(512)
// Set the dh's publicKey
dh.setPublicKey(publicKey)
if (publicKey.equals(dh.getPublicKey()))
console.log("DH public Key is set successfully")
}
运行 index.js 文件,使用以下命令:
node index.js
输出:
DH public Key is set successfully
示例2:
index.js
// Node.js program to demonstrate the
// diffieHellman.setPublicKey() Method
const crypto = require('crypto')
crypto.generateKeyPair(
'dh',
{ primeLength: 512 },
cb
)
function cb(err, publicKey, publicKey) {
// Export key from KeyObject
publicKey = publicKey.export({ type: 'spki', format: 'der' })
// Encode key in base64
publicKey = publicKey.toString('base64');
// Create Diffie-Hellman instance
const dh = crypto.createDiffieHellman(512)
// Set the dh's publicKey
dh.setPublicKey(publicKey, 'base64')
if (publicKey === dh.getPublicKey('base64'))
console.log("DH public Key is set successfully")
}
运行 index.js 文件,使用以下命令:
node index.js
输出:
DH public Key is set successfully
参考资料: https://nodejs.org/api/crypto.html#crypto_diffiehellman_setpublickey_publickey_encoding