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);
输出:
Public Key of Geek A is:
Public Key of Geek B is:
示例 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);
输出:
Public Key of Geek A is: BAECc88Lu8XdEw2wUilULCKCcH0kQC79LilcYuJ92AuUICTIymP3cfStcD5GfkbF329l2wBZr4xwUgQXagyE6isnNAHMoXs2U4eo3NsCmSI2+BxSsJHYWKKim8nJQN8m7VGsQ4D0fpMGnwGFCjouO+V0vBB3ZVEkPfSWKjWytI0Wlf7kxA==
Public Key of Geek B is: 02015ed9d8734b8568583926cb1fa5423d8607458fe236bc92c8652c3beb8c6940e673379b944f39c5549a802eabbe8b6723220b9eaa22293fee76591b9fabbb29d539
参考: https://nodejs.org/api/crypto.html#crypto_ecdh_getpublickey_encoding_format