当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js ECDH.setPublicKey(publicKey[, encoding])用法及代码示例


ecdh.setPublicKey(publicKey[, encoding])

添加于:v0.11.14已弃用:v5.2.0
Stability: 0 - 已弃用

参数

设置 EC Diffie-Hellman 公钥。如果提供了encoding,则publicKey 应该是一个字符串;否则会出现 Buffer TypedArrayDataView

通常没有理由调用此方法,因为ECDH 只需要私钥和对方的公钥来计算共享 key 。通常将调用 ecdh.generateKeys() ecdh.setPrivateKey() ecdh.setPrivateKey() 方法尝试生成与正在设置的私钥关联的公共点/ key 。

示例(获取共享 key ):

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);

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 ECDH.setPublicKey(publicKey[, encoding])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。