Node.js diffieHellman.setPrivateKey() 方法

Node.js diffieHellman.setPrivateKey() 方法

The diffieHellman.setPrivateKey() 方法是加密模块中 DiffieHellman 类(dh)的内置应用程序编程接口,用于设置 dh 对象的私钥。

语法:

diffieHellman.setPrivateKey(privateKey[, encoding])

参数:

该方法接受以下两个参数:

  • privateKey:
    用于表示私钥。
  • encoding:
    用于表示私钥的编码。如果提供了编码,则私钥应为字符串,否则为缓冲区、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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程