diffieHellman.setPrivateKey() 方法是加密模塊中 DiffieHellman (dh) 類的內置應用程序編程接口,用於設置 dh 對象的私鑰。
用法:
diffieHellman.setPrivateKey(privateKey[, encoding])
參數:此方法接受以下兩個參數:
- privateKey:它用於表示私鑰。
- encoding:用於表示privateKey的編碼。如果提供了編碼,privateKey 應為 String,否則為 Buffer、TypedArray 或 DataView。
範例1:
index.js
// Node.js program to demonstrate the
// diffieHellman.setPrivateKey() Method
const crypto = require('crypto')
// Generate DH Key pair
crypto.generateKeyPair('dh',
{
primeLength:512,
publicKeyEncoding:{
type:'spki',
format:'der'
},
privateKeyEncoding:{
type:'pkcs8',
format:'der'
}
},
cb
)
function cb(err, publicKey, privateKey){
// Create Diffie-Hellman instance
const dh = crypto.createDiffieHellman(512)
// Set the dh's privateKey
dh.setPrivateKey(privateKey)
if( privateKey.equals(dh.getPrivateKey()) )
console.log("DH private Key is set successfully")
}
使用以下命令運行 index.js 文件
node index.js
輸出:
DH private Key is set successfully
範例2:
index.js
// Node.js program to demonstrate the
// diffieHellman.setPrivateKey() Method
const crypto = require( 'crypto' )
crypto.generateKeyPair(
'dh',
{ primeLength:512 },
cb
)
function cb( err, publicKey, privateKey ){
// Export key from KeyObject
privateKey = privateKey.export( {type:'pkcs8', format:'der'} )
// Encode key in base64
privateKey = privateKey.toString('base64');
// Create Diffie-Hellman instance
const dh = crypto.createDiffieHellman( 512 )
// Set the dh's privateKey
dh.setPrivateKey( privateKey, 'base64' )
if( privateKey === dh.getPrivateKey('base64') )
console.log( "DH private Key is set successfully" )
}
使用以下命令運行 index.js 文件
node index.js
輸出:
DH private Key is set successfully
參考: https://nodejs.org/api/crypto.html#crypto_ecdh_setprivatekey_privatekey_encoding
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js x509.toLegacyObject()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
注:本文由純淨天空篩選整理自braktim99大神的英文原創作品 Node.js diffieHellman.setPrivateKey() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。