當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。