📜  Node.js ecdh.setPublicKey() 方法

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

Node.js ecdh.setPublicKey() 方法

ecdh.getPublicKey()方法是加密模块中 ECDH 类的内置应用程序编程接口,用于设置椭圆曲线 Diffie-Hellman (ECDH) 对象的公钥。可以使用encoding参数指定密钥的编码。

通常不需要此方法,因为在应用程序中需要计算共享密钥时,可以使用generateKeys()setPrivateKey() 方法 如果公钥对指定曲线无效,则会引发错误。

句法:

ecdh.setPublicKey( publicKey, encoding )

参数:此方法接受上面提到的两个参数,如下所述:

  • publicKey:这是需要设置的公钥。它可以以字符串、ArrayBuffer、Buffer、TypedArray 或 DataView 的格式给出。
  • encoding:这是一个字符串值,指定返回值的编码。它是一个可选参数。

下面的例子演示了这种方法:

示例 1:

Javascript
const crypto = require('crypto');
 
// Generate an ECDH object for geekOne
const geekOne = crypto.createECDH('secp521r1');
 
// Generate a temporary ECDH object
// for generating a public key
const tmpECDH = crypto.createECDH('secp521r1');
 
// Get a temporary public key as a
// Buffer for demonstration
let tempECDHPublicKey = tmpECDH.generateKeys();
 
// Set the public key to be equal to the
// above generated key in the Buffer format
geekOne.setPublicKey(tempECDHPublicKey);
 
// Get the public key that was set
let geekOnePublicKey = geekOne.getPublicKey();
 
console.log("Public Key of Geek A is:",
  geekOnePublicKey);


Javascript
const crypto = require('crypto');
 
// Generate an ECDH object for geekOne
const geekOne = crypto.createECDH('secp521r1');
 
// Generate a key with the encryption
// type as SHA256
let hashObj = crypto.createHash('sha256');
let tempPublicKey =
  hashObj.update('thisisapublickey', 'utf8').digest();
 
// Display the generated key
console.log("The generated key is:", tempPublicKey);
 
// Attempt to set the public key to
// be equal to the above generated key
geekOne.setPublicKey(tempPublicKey);


输出:

示例 2:在此示例中,生成的密钥是不同的曲线。因此,当使用此方法设置此键时,它会引发错误,因为它与 ECDH 对象的曲线不匹配。

Javascript

const crypto = require('crypto');
 
// Generate an ECDH object for geekOne
const geekOne = crypto.createECDH('secp521r1');
 
// Generate a key with the encryption
// type as SHA256
let hashObj = crypto.createHash('sha256');
let tempPublicKey =
  hashObj.update('thisisapublickey', 'utf8').digest();
 
// Display the generated key
console.log("The generated key is:", tempPublicKey);
 
// Attempt to set the public key to
// be equal to the above generated key
geekOne.setPublicKey(tempPublicKey);

输出:

参考: https://nodejs.org/api/crypto.html#crypto_ecdh_setpublickey_publickey_encoding