Node.JS crypto.ECDH.computeSecret() 总是抛出错误

Node.JS crypto.ECDH.computeSecret() always throw an error

我创建了一个测试程序来测试 Node.JS 文档中的 ECDH 算法。我修改了代码以用于我的远程应用程序,代码如下所示:

//Source
var crypto = require('crypto');
var fs = require('fs');
var ecdh = crypto.createECDH('secp521r1');
fs.writeFileSync('./key',ecdh.generateKeys().toString('base64'));
//Remote
var crypto = require('crypto');
var fs = require('fs');
var ecdh = crypto.createECDH('secp521r1');
ecdh.generateKeys();
var key = Buffer.from(fs.readFileSync('./key'), 'base64');
var secret = ecdh.computeSecret(key, 'base64');
console.log(secret);

但是,每次我从远程脚本 运行 ECDH.computeSecret() 时,它总是会抛出错误。我试过寻找解决方案,但无处可寻。

终于找到问题了,是因为我存盘时忘记指定编码了。网络上应该是一样的。

//source
var crypto = require('crypto');
var fs = require('fs');
var ecdh = crypto.createECDH('secp521r1');
fs.writeFileSync('./key', ecdh.generateKeys().toString('base64'), {encoding: 'utf-8'}); //added encoding
//Remote
var crypto = require('crypto');
var fs = require('fs');
var ecdh = crypto.createECDH('secp521r1');
ecdh.generateKeys();
var key = Buffer.from(fs.readFileSync('./key', {encoding: 'utf-8'}), 'base64');//added encoding
var secret = ecdh.computeSecret(key);
console.log(secret)