Node.js ecdh.getPrivateKey() 方法
ecdh.getPrivateKey()方法是加密模块中 ECDH 类的内置应用程序编程接口,用于获取椭圆曲线 Diffie-Hellman (ECDH) 对象的私钥。可以使用encoding参数指定密钥的编码,使用format参数指定格式。
注意:必须先使用generateKeys()方法生成密钥,然后才能使用私钥检索它们。
句法:
ecdh.getPrivateKey( encoding )
参数:此方法接受如上所述和如下所述的单个参数:
- encoding:这是一个字符串值,指定返回值的编码。它是一个可选参数。
- format:它是一个字符串,用于指定键的格式。该值可以是“压缩的”或“未压缩的”。它是一个可选参数。
返回值:返回指定编码的椭圆曲线DiffieHellman私钥。如果未提供编码,则作为 Buffer 返回,否则返回 String。
下面的例子演示了这种方法:
示例 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 private key for geekA
const geekAprivateKey = geekA.getPrivateKey();
console.log("Private Key of Geek A is:",
geekAprivateKey);
// Get the private key for geekB
const geekBprivateKey = geekB.getPrivateKey();
console.log("Private Key of Geek B is:",
geekBprivateKey);
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 private key for geekA in base64
const geekAPrivateKey =
geekA.getPrivateKey('base64');
console.log("Private Key of Geek A is:",
geekAPrivateKey);
// Get the private key for geekB in hex
const geekBPrivateKey =
geekB.getPrivateKey('hex');
console.log("Private Key of Geek B is:",
geekBPrivateKey);
输出:
Private Key of Geek A is:
Private 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 private key for geekA in base64
const geekAPrivateKey =
geekA.getPrivateKey('base64');
console.log("Private Key of Geek A is:",
geekAPrivateKey);
// Get the private key for geekB in hex
const geekBPrivateKey =
geekB.getPrivateKey('hex');
console.log("Private Key of Geek B is:",
geekBPrivateKey);
输出:
Private Key of Geek A is: AXZvAlAJi4U5gL0Hj+kkriNlH45k+UkIz27MD0x4jsbKTjEUcU8vTUFvcw3aLHt4lit+V1Jp6fQ/4MH2dFNlfpu6
Private Key of Geek B is: 0152465d0c729f46f1f78532fde54eb0218b491e5a87926120862b79de9084e7a78f604de4d4d9f4c31ab7819bf6cf8f0d75849781ad556fed947ad968e008c90940
参考: https://nodejs.org/api/crypto.html#crypto_ecdh_getprivatekey_encoding