Node.js ecdh.generateKeys() 方法
ecdh.generateKeys() 方法是加密模块内 class ECDH 的内置应用程序编程接口,用于生成椭圆曲线迪菲-赫尔曼(ECDH)对象的私钥和公钥值。它只返回给定格式和编码的公钥。
语法:
ecdh.generateKeys( encoding, format )
参数:
- encoding:
这是一个字符串值,用于指定返回值的编码。- format: 这是一个字符串,用于指定键的格式。其值可以是“compressed”或“uncompressed”。
返回值:
它返回指定编码的椭圆曲线Diffie-Hellman公钥。如果未提供编码,则返回一个Buffer,否则返回一个字符串。
下面的示例演示了该方法:
示例1:
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);
输出:
Geek A的公钥是: Geek A的私钥是:
示例2:
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);
输出:
极客A的公钥是:BAHbKH6Uv0hAZPhQer+bVA/GC8VRqTf0LTLpNWmWeOPh+pDkLhhHnE9/XYI2pjDQ1Nhum/GeHkOEJKSMEaD51Q0EhgE2y+IiHb2gSluy7ho0OosMLFrlM8YgPaXNV6skBqsbNGlYh/HEBIlilzNfGUrNsvsh4RuI0usEOh/v6NFrpEIfUA==
极客B的公钥是:AwCz/x81YIdVtPyy5B3YKwgR3hgzOXrFZsXi3M2WFcvRL2yh0VKza0/b8Mw1Z/p4Pnl1gGO2JMUfLNI4FFvzaxb9Og==
参考: https://nodejs.org/api/crypto.html#crypto_ecdh_generatekeys_encoding_format