ecdh.setPublicKey(publicKey[, encoding])
¥Stability: 0 - Deprecated
-
publicKey
<string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>
设置 EC Diffie-Hellman 公钥。如果提供了 encoding
,则 publicKey
应该是一个字符串;否则应为 Buffer
、TypedArray
或 DataView
。
¥Sets the EC Diffie-Hellman public key.
If encoding
is provided publicKey
is expected to
be a string; otherwise a Buffer
, TypedArray
, or DataView
is expected.
通常没有理由调用这个方法,因为 ECDH
只需要一个私钥和对方的公钥来计算共享秘密。通常会调用 ecdh.generateKeys()
或 ecdh.setPrivateKey()
。ecdh.setPrivateKey()
方法尝试生成与正在设置的私钥相关联的公共点/密钥。
¥There is not normally a reason to call this method because ECDH
only requires a private key and the other party's public key to compute the
shared secret. Typically either ecdh.generateKeys()
or
ecdh.setPrivateKey()
will be called. The ecdh.setPrivateKey()
method
attempts to generate the public point/key associated with the private key being
set.
示例(获取共享密钥):
¥Example (obtaining a shared secret):
const {
createECDH,
createHash,
} = await import('node:crypto');
const alice = createECDH('secp256k1');
const bob = createECDH('secp256k1');
// This is a shortcut way of specifying one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
createHash('sha256').update('alice', 'utf8').digest(),
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
const {
createECDH,
createHash,
} = require('node:crypto');
const alice = createECDH('secp256k1');
const bob = createECDH('secp256k1');
// This is a shortcut way of specifying one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
createHash('sha256').update('alice', 'utf8').digest(),
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);