node.js - 使用加密模块从 node.js 中的 Curve25519(或 X25519)非对称密钥对生成共享密钥
问题描述
我正在尝试使用密钥交换算法在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'));
这缺少身份验证,因此如果不添加该部分是不安全的。
推荐阅读
- c++ - Cpp - 通过 SOCKET 网络的 Python 连接
- javascript - 表格未附加到我的 html 中的特定 div 'contactsearchtable'
- excel - 循环工作表以从现有表创建数据透视表
- javascript - 尽管事件触发,React 组件仍不呈现
- javascript - 如何使用 javascript 从我的麦克风获取音频?
- java - PDFBox renderImageWithDPI 有时会挂起
- python - Django:表单集 CBV 上的 save(commit=False) 正在触发自定义模型 save() 操作
- python - Django:“产品匹配查询不存在。”?
- javascript - 试图实现 angularJs $uibModal 但它没有弹出。给出错误 angular.min.js:129 可能未处理的拒绝:背景点击
- visual-studio - Visual Studio 资源编辑器 ActiveX 控件...在我刚刚使用资源编辑器添加后无法实例化?