diff --git a/src/ephemeral-keys.js b/src/ephemeral-keys.js index ff2f5c2..53fa808 100644 --- a/src/ephemeral-keys.js +++ b/src/ephemeral-keys.js @@ -22,10 +22,11 @@ module.exports = (curveName) => { const priv = ec.genKeyPair() - const genSharedKey = (theirPub) => { + // forcePrivate is used for testing only + const genSharedKey = (theirPub, forcePrivate) => { const pub = ec.keyFromPublic(theirPub, 'hex') - - return priv.derive(pub.getPublic()).toBuffer('le') + const p = forcePrivate || priv + return p.derive(pub.getPublic()).toBuffer('le') } return { diff --git a/test/ephemeral-keys.spec.js b/test/ephemeral-keys.spec.js index 30cec4e..a7e83ca 100644 --- a/test/ephemeral-keys.spec.js +++ b/test/ephemeral-keys.spec.js @@ -2,8 +2,10 @@ 'use strict' const expect = require('chai').expect +const EC = require('elliptic').ec const crypto = require('../src') +const fixtures = require('./fixtures/go-elliptic-key') describe('generateEphemeralKeyPair', () => { it('returns a function that generates a shared secret', () => { @@ -18,4 +20,25 @@ describe('generateEphemeralKeyPair', () => { res.key ).to.exist }) + + describe('go interop', () => { + it('generates a shared secret', () => { + const curve = fixtures.curve + const ec = new EC(fixtures.curveJs) + const bobPrivate = ec.keyFromPrivate(fixtures.bob.private, 'binary') + + const alice = crypto.generateEphemeralKeyPair(curve) + const bob = { + key: fixtures.bob.public, + // this is using bobs private key from go ipfs + // instead of alices + genSharedKey: (key) => alice.genSharedKey(key, bobPrivate) + } + + const s1 = alice.genSharedKey(bob.key) + const s2 = bob.genSharedKey(alice.key) + + expect(s1.equals(s2)).to.be.eql(true) + }) + }) }) diff --git a/test/fixtures/go-elliptic-key.js b/test/fixtures/go-elliptic-key.js new file mode 100644 index 0000000..1f08faf --- /dev/null +++ b/test/fixtures/go-elliptic-key.js @@ -0,0 +1,14 @@ +'use strict' + +module.exports = { + curve: 'P-256', + curveJs: 'p256', + bob: { + private: [ + 231, 236, 69, 16, 13, 92, 76, 83, 75, 40, 32, 71, 235, 187, 29, 214, 98, 231, 42, 5, 80, 89, 58, 175, 8, 95, 86, 50, 44, 214, 4, 172 + ], + public: new Buffer([ + 4, 160, 169, 215, 85, 152, 11, 209, 69, 105, 17, 51, 49, 83, 214, 171, 157, 73, 165, 85, 28, 196, 161, 234, 87, 149, 139, 76, 123, 37, 174, 194, 67, 167, 18, 34, 164, 35, 171, 164, 238, 141, 199, 206, 86, 130, 183, 88, 63, 121, 110, 150, 229, 10, 213, 176, 181, 1, 98, 20, 246, 85, 212, 200, 229 + ]) + } +}