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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP