📜  Node.js diffieHellman.setPublicKey() 方法

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

Node.js diffieHellman.setPublicKey() 方法

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

句法:

diffieHellman.setPublicKey(publicKey[, encoding])

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

  • publicKey:用于表示私钥。
  • encoding:用于表示publicKey的编码。如果提供了编码,则publicKey应为 String,否则为 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.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

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