📜  Node.js diffieHellman.setPrivateKey() 方法

📅  最后修改于: 2022-05-13 01:56:48.280000             🧑  作者: Mango

Node.js diffieHellman.setPrivateKey() 方法

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.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

示例 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