Node.js ecdh.setPrivateKey() 方法
ecdh.getPrivateKey()方法是加密模块中 ECDH 类的内置应用程序编程接口,用于设置椭圆曲线 Diffie-Hellman (ECDH) 对象的私钥。可以使用encoding参数指定密钥的编码。
如果私钥对指定曲线无效,则会引发错误。使用该方法设置私钥会自动生成并设置ECDH对象中对应的公钥。
句法:
ecdh.setPrivateKey( privateKey, encoding )
参数:此方法接受上面提到的两个参数,如下所述:
- privateKey:这是需要设置的私钥。它可以以字符串、ArrayBuffer、Buffer、TypedArray 或 DataView 的格式给出。
- encoding:在编码字符串值中指定返回值的编码。它是一个可选参数。
返回值:返回指定编码的椭圆曲线 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');
// Create a private key of geekA
geekA.setPrivateKey("thisisasecretkey!");
// Create a private key of geekB
geekB.setPrivateKey("thisisanotherkey!");
// Get the private keys of both the geeks
let geekAPrivateKey = geekA.getPrivateKey();
let geekBPrivateKey = geekB.getPrivateKey();
console.log("Private Key of Geek A is:",
geekAPrivateKey);
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');
// Create a private key of geekA
// with "hello" in hex format
geekA.setPrivateKey("68656c6c6f", "hex");
// Create a private key of geekB
// with "world" in base64 format
geekB.setPrivateKey("d29ybGQ=", "base64");
// Get the private keys of both the geeks
// in 'utf-8' encoding
let geekAPrivateKey =
geekA.getPrivateKey('utf-8');
let geekBPrivateKey =
geekB.getPrivateKey('utf-8');
console.log("Private Key of Geek A is:",
geekAPrivateKey);
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');
// Create a private key of geekA
// with "hello" in hex format
geekA.setPrivateKey("68656c6c6f", "hex");
// Create a private key of geekB
// with "world" in base64 format
geekB.setPrivateKey("d29ybGQ=", "base64");
// Get the private keys of both the geeks
// in 'utf-8' encoding
let geekAPrivateKey =
geekA.getPrivateKey('utf-8');
let geekBPrivateKey =
geekB.getPrivateKey('utf-8');
console.log("Private Key of Geek A is:",
geekAPrivateKey);
console.log("Private Key of Geek B is:",
geekBPrivateKey);
输出:
Private Key of Geek A is: hello
Private Key of Geek B is: world
参考: https://nodejs.org/api/crypto.html#crypto_ecdh_setprivatekey_privatekey_encoding