📜  Node.js ecdh.getPublicKey() 方法

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

Node.js ecdh.getPublicKey() 方法

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

必须首先使用generateKeys()方法生成密钥,然后才能使用公钥检索它们。

句法:

ecdh.getPublicKey( encoding, format )

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

  • encoding:这是一个字符串值,指定返回值的编码。
  • format:它是一个字符串,用于指定键的格式。该值可以是“压缩的”或“未压缩的”。

返回值:返回指定编码的椭圆曲线 DiffieHellman 公钥。如果未提供编码,则作为缓冲区返回,否则返回字符串。

示例 1:以下示例演示了此方法:

Javascript
const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate the keys for both the geeks
geekA.generateKeys();
geekB.generateKeys();
  
// Get the public key for geekA
const geekAPublicKey = geekA.getPublicKey();
  
console.log("Public Key of Geek A is:", geekAPublicKey);
  
// Generate keys for geekB
const geekBPublicKey = geekB.getPublicKey();
  
console.log("Public Key of Geek B is:", geekBPublicKey);


Javascript
const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate the keys for both the geeks
geekA.generateKeys();
geekB.generateKeys();
  
// Get the public key for geekA in base64
const geekAPublicKey = 
  geekA.getPublicKey('base64');
  
console.log(
  "Public Key of Geek A is:", geekAPublicKey);
  
// Generate keys for geekB in hex in
// the compressed format
const geekBPublicKey =
  geekB.getPublicKey('hex', 'compressed');
  
console.log(
  "Public Key of Geek B is:", geekBPublicKey);


输出:

示例 2:

Javascript

const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate the keys for both the geeks
geekA.generateKeys();
geekB.generateKeys();
  
// Get the public key for geekA in base64
const geekAPublicKey = 
  geekA.getPublicKey('base64');
  
console.log(
  "Public Key of Geek A is:", geekAPublicKey);
  
// Generate keys for geekB in hex in
// the compressed format
const geekBPublicKey =
  geekB.getPublicKey('hex', 'compressed');
  
console.log(
  "Public Key of Geek B is:", geekBPublicKey);

输出:

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