簡體   English   中英

使用加密模塊從 node.js 中的 Curve25519(或 X25519)非對稱密鑰對生成共享密鑰

[英]Generate shared secret key from Curve25519 (or X25519) asymmetric key pairs in node.js using crypto module

我正在嘗試使用密鑰交換算法在Curve25519(或 X25519)非對稱密鑰對之間創建共享密鑰,就像Diffie Hellman key exchange一樣。 Diffie Hellman密鑰交換可以在 node.js 中使用以下代碼中的加密模塊完成:

const crypto = require('crypto');

// Generate Alice's keys...
const alice = crypto.createDiffieHellman(2048);
const aliceKey = alice.generateKeys(); // Returns public key

// Generate Bob's keys...
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys(); // Returns public key

// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);

// Should be equal
console.log(aliceSecret === bobSecret)

可以使用以下代碼生成X25519 非對稱密鑰

const crypto = require('crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519', {
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
  }
});

生成的密鑰沒有任何問題,但我不知道如何生成共享密鑰。 我嘗試使用以下代碼將 X25519 密鑰轉換為Diffie Hellman密鑰:

...
const dhKey= crypto.createDiffieHellman(2048);
// privateKey => Generated in the above code
dhKey.setPrivateKey(privateKey)
// publicKey => Generated in the above code
dhKey.setPublicKey(publicKey)
...

在生成兩個 dhKey 並執行密鑰交換時使用上述代碼時,會出現以下錯誤:

Error: Supplied key is too large

有什么方法可以生成共享秘密? 提前致謝。

不幸的是,這個子 API 的文檔有點薄。 我拼湊了一個示例,但沒有更好的文檔,我不確定它是否有用。

const crypto = require('crypto');

const aliceKeyPair = crypto.generateKeyPairSync('x25519');

const alicePubExport = aliceKeyPair.publicKey.export(
    {type: 'spki', format: 'pem'}
    );

const bobKeyPair = crypto.generateKeyPairSync('x25519');

const bobPubExport = bobKeyPair.publicKey.export(
    {type: 'spki', format: 'pem'}
    );

const bobKeyAgree = crypto.diffieHellman({
    publicKey : crypto.createPublicKey(alicePubExport),
    privateKey: bobKeyPair.privateKey
});

const aliceKeyAgree = crypto.diffieHellman({
    publicKey : crypto.createPublicKey(bobPubExport),
    privateKey: aliceKeyPair.privateKey
});

console.log(bobKeyAgree.toString('hex'));
console.log(aliceKeyAgree.toString('hex'));

這缺少身份驗證,因此如果不添加該部分是不安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM