Node.js ecdh.computeSecret() 方法
ecdh.computeSecret() 方法是加密模块中 ECDH 类的内置应用程序接口,用于使用对方的公钥创建共享密钥。可以使用相应的参数来指定输入公钥和输出密钥的编码方式。
当公钥位于椭圆曲线之外时,会抛出 ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY 错误。
语法:
ecdh.computeSecret( otherPublicKey, inputEncoding, outputEncoding )
参数: 此方法接受如上所述并在下面描述的三个参数:
- otherPublicKey: 这是基于第二方的公钥生成的共享密钥。
- inputEncoding: 这是一个字符串值,用于指定第二方公钥的编码。当未指定此参数时,该密钥预期为缓冲区的TypedArray或DataView。
- outputEncoding: 这是一个字符串值,用于指定将生成的共享密钥的编码方式。
返回值: 返回指定编码方式的椭圆曲线Diffie-Hellman共享密钥。当未提供编码时,返回缓冲区,否则返回字符串。
下面的示例演示了该方法:
示例1: 在此示例中,使用两个方的密钥创建了两个用户的共享密钥,然后将它们进行比较以查看它们是否相等。
const crypto = require('crypto');
const geekA = crypto.createECDH('secp521r1');
// Generate keys for geekA
const geekAkey = geekA.generateKeys('base64');
const geekB = crypto.createECDH('secp521r1');
// Generate keys for geekB
const geekBkey = geekB.generateKeys('base64');
// Compute the secrets of both the geeks in base64
// based on the other party's key
let secretA = geekA.computeSecret(geekBkey, 'base64', 'base64');
let secretB = geekB.computeSecret(geekAkey, 'base64', 'base64');
console.log("Secret of A is:", secretA);
console.log("Secret of B is:", secretB);
// Check if the secrets match
console.log(secretA == secretB ?
"The secrets match!" :
"The secrets do not match")
输出:
A的密钥是:Ac7p1CjFXyTrdcVxx0HIs0Jqjr3fGb7sUTxfgdUQ+xgXmpJgWKS9SECkFf3ehly+xyvE2MtWFcAxF2gq9F7k7tT5
B的密钥是:Ac7p1CjFXyTrdcVxx0HIs0Jqjr3fGb7sUTxfgdUQ+xgXmpJgWKS9SECkFf3ehly+xyvE2MtWFcAxF2gq9F7k7tT5
密钥匹配!
示例2: 在这个示例中,输入编码参数设置为null,因为generateKeys()方法在生成密钥时不对其进行编码。
const crypto = require('crypto');
const geekOne = crypto.createECDH('secp521r1');
// Generate keys for geekOne
const geekOneKey = geekOne.generateKeys();
const geekTwo = crypto.createECDH('secp521r1');
// Generate keys for geekTwo
const geekTwoKey = geekTwo.generateKeys();
// Compute the secrets of both the geeks
// The input
let secretGeekOne =
geekOne.computeSecret(geekTwoKey, null, 'base64');
let secretGeekTwo =
geekTwo.computeSecret(geekOneKey, null, 'base64');
console.log("Secret of Geek One is:", secretGeekOne);
console.log("Secret of Geek Two is:", secretGeekTwo);
输出:
Geek One 的密钥是:ACc+SKe9XQMw5quzSEKs0Os+OhGKPRqHIwkW13+lxhs2HNwUEvbZdCEOE/PCzdNKk3v5zqdWSHO0kfRy1qBM8Kc6
Geek Two 的密钥是:ACc+SKe9XQMw5quzSEKs0Os+OhGKPRqHIwkW13+lxhs2HNwUEvbZdCEOE/PCzdNKk3v5zqdWSHO0kfRy1qBM8Kc6
参考: https://nodejs.org/api/crypto.html#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding