Search code examples
node.jscryptographydiffie-hellmanecdh

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


I created a test program to test ECDH algorithm from Node.JS documentation. I adapted the code to be used with my remote application, and the code looks like this:

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

However, every time I run ECDH.computeSecret() from remote script, it always throw an error. I've tried finding solutions, but nowhere to be found.


Solution

  • I finally found a problem, it's just because I forgot to specify the encoding while saving a key to a disk. On the network, it should be the same.

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