📜  Node.js ecdh.generateKeys() 方法

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

Node.js ecdh.generateKeys() 方法

ecdh.generateKeys()方法是加密模块中 ECDH 类的内置应用程序编程接口,用于生成椭圆曲线 Diffie-Hellman (ECDH) 对象的私钥和公钥值。它仅返回给定格式和编码的公钥。

句法:

ecdh.generateKeys( encoding, format )

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

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

返回值:返回指定编码的椭圆曲线 DiffieHellman 公钥。未提供编码时,作为 Buffer 返回,否则返回 String。

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

示例 1:

Javascript
const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geek = crypto.createECDH('secp521r1');
  
// Generate keys for geek and return
// the public key
const geekAPublicKey = geek.generateKeys();
  
console.log(
  "Public Key of Geek A is:", geekAPublicKey);
  
// Get the private key of geek
const geekAPrivateKey = geek.getPrivateKey();
console.log(
  "Private Key of Geek A is:", geekAPrivateKey);


Javascript
const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate keys for geekA in base64 encoding
const geekAkey =
  geekA.generateKeys('base64');
  
console.log(
  "Public Key of Geek A is:", geekAkey);
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate keys for geekB in base64
// encoding and compressed
const geekBkey =
  geekB.generateKeys('base64', 'compressed');
  
console.log(
  "Public Key of Geek B is:", geekBkey);


输出:

示例 2:

Javascript

const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate keys for geekA in base64 encoding
const geekAkey =
  geekA.generateKeys('base64');
  
console.log(
  "Public Key of Geek A is:", geekAkey);
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate keys for geekB in base64
// encoding and compressed
const geekBkey =
  geekB.generateKeys('base64', 'compressed');
  
console.log(
  "Public Key of Geek B is:", geekBkey);

输出:

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