refactor: use libp2p and standardized rsa keys

This commit is contained in:
dignifiedquire 2016-05-23 22:06:25 +02:00
parent 7635cfcfda
commit 4beb1f8888
4 changed files with 200 additions and 200 deletions

View File

@ -33,29 +33,17 @@
"homepage": "https://github.com/diasdavid/js-peer-id",
"devDependencies": {
"aegir": "^3.0.4",
"buffer-loader": "0.0.1",
"chai": "^3.5.0",
"pre-commit": "^1.1.2"
},
"dependencies": {
"bs58": "^3.0.0",
"multihashing": "^0.2.0",
"node-forge": "^0.6.38",
"protocol-buffers": "^3.1.4"
"libp2p-crypto": "^0.4.0",
"multihashes": "^0.2.2"
},
"repository": {
"type": "git",
"url": "https://github.com/diasdavid/js-peer-id.git"
},
"aegir": {
"webpack": {
"resolve": {
"alias": {
"node-forge": "../vendor/forge.bundle.js"
}
}
}
},
"contributors": [
"David Dias <daviddias.p@gmail.com>",
"David Dias <mail@daviddias.me>",

View File

@ -1,13 +0,0 @@
enum KeyType {
RSA = 0;
}
message PublicKey {
required KeyType Type = 1;
required bytes Data = 2;
}
message PrivateKey {
required KeyType Type = 1;
required bytes Data = 2;
}

View File

@ -4,137 +4,102 @@
'use strict'
const fs = require('fs')
const multihashing = require('multihashing')
const base58 = require('bs58')
const forge = require('node-forge')
const protobuf = require('protocol-buffers')
const path = require('path')
const mh = require('multihashes')
const crypto = require('libp2p-crypto')
const assert = require('assert')
const pbCrypto = protobuf(fs.readFileSync(path.resolve(__dirname, '../protos/crypto.proto')))
class PeerId {
constructor (id, privKey, pubKey) {
if (Buffer.isBuffer(id)) {
this.id = id
} else {
throw new Error('invalid id provided')
}
exports = module.exports = PeerId
if (pubKey) {
assert(this.id.equals(pubKey.hash()), 'inconsistent arguments')
}
exports.Buffer = Buffer
if (privKey) {
assert(this.id.equals(privKey.public.hash()), 'inconsistent arguments')
}
function PeerId (id, privKey, pubKey) {
const self = this
if (privKey && pubKey) {
assert(privKey.public.bytes.equals(pubKey.bytes), 'inconsistent arguments')
}
if (!(self instanceof PeerId)) {
throw new Error('Id must be called with new')
this.privKey = privKey
this._pubKey = pubKey
}
self.privKey = privKey
self.pubKey = pubKey
self.id = id // multihash - sha256 - buffer
get pubKey () {
if (this._pubKey) {
return this._pubKey
}
// pretty print
self.toPrint = function () {
return {
id: self.toB58String(),
privKey: privKey.toString('hex'),
pubKey: pubKey.toString('hex')
if (this.privKey) {
return this.privKey.public
}
}
self.toJSON = function () {
marshalPubKey () {
if (this.pubKey) {
return crypto.marshalPublicKey(this.pubKey)
}
}
marshalPrivKey () {
if (this.privKey) {
return crypto.marshalPrivateKey(this.privKey)
}
}
// pretty print
toPrint () {
return {
id: self.id.toString('hex'),
privKey: self.privKey.toString('hex'),
pubKey: self.pubKey.toString('hex')
id: mh.toB58String(this.id),
privKey: toHexOpt(this.marshalPrivKey()),
pubKey: toHexOpt(this.marshalPubKey())
}
}
toJSON () {
return {
id: mh.toHexString(this.id),
privKey: toHexOpt(this.marshalPrivKey()),
pubKey: toHexOpt(this.marshalPubKey())
}
}
// encode/decode functions
self.toHexString = function () {
return self.id.toString('hex')
toHexString () {
return mh.toHexString(this.id)
}
self.toBytes = function () {
return self.id
toBytes () {
return this.id
}
self.toB58String = function () {
return base58.encode(self.id)
toB58String () {
return mh.toB58String(this.id)
}
}
// unwrap the private key protobuf
function keyUnmarshal (key) {
return pbCrypto.PrivateKey.decode(key)
}
// create a public key protobuf to be base64 string stored in config
function keyMarshal (data, type) {
const RSA = 0
let epb
if (type === 'Public') {
epb = pbCrypto.PublicKey.encode({
Type: RSA,
Data: data
})
}
if (type === 'Private') {
epb = pbCrypto.PrivateKey.encode({
Type: RSA,
Data: data
})
}
return epb
}
// this returns a base64 encoded protobuf of the public key
function formatKey (key, type) {
// create der buffer of public key asn.1 object
const der = forge.asn1.toDer(key)
// create forge buffer of der public key buffer
const fDerBuf = forge.util.createBuffer(der.data, 'binary')
// convert forge buffer to node buffer public key
const nDerBuf = new Buffer(fDerBuf.getBytes(), 'binary')
// protobuf the new DER bytes to the PublicKey Data: field
const marsheledKey = keyMarshal(nDerBuf, type)
// encode the protobuf public key to base64 string
const b64 = marsheledKey.toString('base64')
return b64
}
exports = module.exports = PeerId
exports.Buffer = Buffer
// generation
exports.create = function (opts) {
opts = opts || {}
opts.bits = opts.bits || 2048
// generate keys
const pair = forge.rsa.generateKeyPair({
bits: opts.bits,
e: 0x10001
})
const privKey = crypto.generateKeyPair('RSA', opts.bits)
// return the RSA public/private key to asn1 object
const asnPub = forge.pki.publicKeyToAsn1(pair.publicKey)
const asnPriv = forge.pki.privateKeyToAsn1(pair.privateKey)
// format the keys to protobuf base64 encoded string
const protoPublic64 = formatKey(asnPub, 'Public')
const protoPrivate64 = formatKey(asnPriv, 'Private')
// store the keys as a buffer
const bufProtoPub64 = new Buffer(protoPublic64, 'base64')
const bufProtoPriv64 = new Buffer(protoPrivate64, 'base64')
const mhId = multihashing(new Buffer(protoPublic64, 'base64'), 'sha2-256')
return new PeerId(mhId, bufProtoPriv64, bufProtoPub64)
return new PeerId(privKey.public.hash(), privKey)
}
exports.createFromHexString = function (str) {
return new PeerId(new Buffer(str, 'hex'))
return new PeerId(mh.fromHexString(str))
}
exports.createFromBytes = function (buf) {
@ -142,51 +107,47 @@ exports.createFromBytes = function (buf) {
}
exports.createFromB58String = function (str) {
return new PeerId(new Buffer(base58.decode(str)))
return new PeerId(mh.fromB58String(str))
}
// Public Key input will be a buffer
exports.createFromPubKey = function (pubKey) {
const buf = new Buffer(pubKey, 'base64')
const mhId = multihashing(buf, 'sha2-256')
return new PeerId(mhId, null, pubKey)
exports.createFromPubKey = function (key) {
let buf = key
if (typeof buf === 'string') {
buf = new Buffer(key, 'base64')
}
const pubKey = crypto.unmarshalPublicKey(buf)
return new PeerId(pubKey.hash(), null, pubKey)
}
// Private key input will be a string
exports.createFromPrivKey = function (privKey) {
// create a buffer from the base64 encoded string
const buf = new Buffer(privKey, 'base64')
exports.createFromPrivKey = function (key) {
let buf = key
if (typeof buf === 'string') {
buf = new Buffer(key, 'base64')
}
// get the private key data from the protobuf
const mpk = keyUnmarshal(buf)
// create a forge buffer
const fbuf = forge.util.createBuffer(mpk.Data.toString('binary'))
// create an asn1 object from the private key bytes saved in the protobuf Data: field
const asnPriv = forge.asn1.fromDer(fbuf)
// get the RSA privatekey data from the asn1 object
const privateKey = forge.pki.privateKeyFromAsn1(asnPriv)
// set the RSA public key to the modulus and exponent of the private key
const publicKey = forge.pki.rsa.setPublicKey(privateKey.n, privateKey.e)
// return the RSA public key to asn1 object
const asnPub = forge.pki.publicKeyToAsn1(publicKey)
// format the public key
const protoPublic64 = formatKey(asnPub, 'Public')
// buffer the public key for consistency before storing
const bufProtoPub64 = new Buffer(protoPublic64, 'base64')
const mhId = multihashing(new Buffer(protoPublic64, 'base64'), 'sha2-256')
return new PeerId(mhId, privKey, bufProtoPub64)
const privKey = crypto.unmarshalPrivateKey(buf)
return new PeerId(privKey.public.hash(), privKey)
}
exports.createFromJSON = function (obj) {
return new PeerId(
new Buffer(obj.id, 'hex'),
new Buffer(obj.privKey, 'hex'),
new Buffer(obj.pubKey, 'hex'))
let priv
let pub
if (obj.privKey) {
priv = crypto.unmarshalPrivateKey(new Buffer(obj.privKey, 'hex'))
}
if (obj.pubKey) {
pub = crypto.unmarshalPublicKey(new Buffer(obj.pubKey, 'hex'))
}
return new PeerId(mh.fromHexString(obj.id), priv, pub)
}
function toHexOpt (val) {
if (val) {
return val.toString('hex')
}
}

View File

@ -2,6 +2,8 @@
'use strict'
const expect = require('chai').expect
const crypto = require('libp2p-crypto')
const PeerId = require('../src')
const testId = {
@ -16,89 +18,151 @@ const testIdBytes = new Buffer('1220151ab1658d8294ab34b71d5582cfe20d06414212f440
const testIdB58String = 'QmQ2zigjQikYnyYUSXZydNXrDRhBut2mubwJBaLXobMt3A'
describe('id', function (done) {
this.timeout(30000)
it('create an id without \'new\'', (done) => {
describe('PeerId', () => {
it('create an id without \'new\'', () => {
expect(PeerId).to.throw(Error)
done()
})
it('create a new id', (done) => {
it('create a new id', () => {
const id = PeerId.create()
expect(id.toB58String().length).to.equal(46)
done()
})
it('recreate an Id from Hex string', (done) => {
it('recreate an Id from Hex string', () => {
const id = PeerId.createFromHexString(testIdHex)
expect(testIdBytes).to.deep.equal(id.id)
done()
})
it('Recreate an Id from a Buffer', (done) => {
it('Recreate an Id from a Buffer', () => {
const id = PeerId.createFromBytes(testIdBytes)
expect(testId.id).to.equal(id.toHexString())
done()
})
it('Recreate a B58 String', (done) => {
it('Recreate a B58 String', () => {
const id = PeerId.createFromB58String(testIdB58String)
expect(testIdB58String).to.equal(id.toB58String())
done()
})
it('Recreate from a Public Key', (done) => {
it('Recreate from a Public Key', () => {
const id = PeerId.createFromPubKey(testId.pubKey)
expect(testIdB58String).to.equal(id.toB58String())
done()
})
it('Recreate from a Private Key', (done) => {
it('Recreate from a Private Key', () => {
const id = PeerId.createFromPrivKey(testId.privKey)
expect(testIdB58String).to.equal(id.toB58String())
done()
const id2 = PeerId.createFromPrivKey(new Buffer(testId.privKey, 'base64'))
expect(testIdB58String).to.equal(id2.toB58String())
})
it('Compare generated ID with one created from PubKey', (done) => {
it('Compare generated ID with one created from PubKey', () => {
const id1 = PeerId.create()
const id2 = PeerId.createFromPubKey(id1.pubKey)
expect(id2.id).to.deep.equal(id1.id)
done()
const id2 = PeerId.createFromPubKey(id1.marshalPubKey())
expect(id1.id).to.be.eql(id2.id)
})
it('Non-default # of bits', (done) => {
it('Non-default # of bits', () => {
const shortId = PeerId.create({ bits: 128 })
const longId = PeerId.create({ bits: 256 })
expect(shortId.privKey.length).is.below(longId.privKey.length)
done()
expect(shortId.privKey.bytes.length).is.below(longId.privKey.bytes.length)
})
it('Pretty printing', (done) => {
it('Pretty printing', () => {
const id = PeerId.createFromPrivKey(testId.privKey)
var out = id.toPrint()
var expected = {
const out = id.toPrint()
const expected = {
id: 'QmQ2zigjQikYnyYUSXZydNXrDRhBut2mubwJBaLXobMt3A',
privKey: 'CAASpgkwggSiAgEAAoIBAQC2SKo/HMFZeBml1AF3XijzrxrfQXdJzjePBZA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Fk+6yGk9Vw4Hf46B+82SvOrSbmnMa+PYqKYIvUzR4gg34rL/7AhwnbEyD5hXq4dHwMNsIDq+l2elPjwm/U9V0gdAl2+r50HAoGALtsKqMvhv8HucAMBPrLikhXP/8um8mMKFMrzfqZ+otxfHzlhI0L08Bo3jQrb0Z7ByNY6M8epOmbCKADsbWcVre/AAY0ZkuSZK/CaOXNX/AhMKmKJh8qAOPRY02LIJRBCpfS4czEdnfUhYV/TYiFNnKRj57PPYZdTzUsxa/yVTmECgYBr7slQEjb5Onn5mZnGDh+72BxLNdgwBkhO0OCdpdISqk0F0Pxby22DFOKXZEpiyI9XYP1C8wPiJsShGm2yEwBPWXnrrZNWczaVuCbXHrZkWQogBDG3HGXNdU4MAWCyiYlyinIBpPpoAJZSzpGLmWbMWh28+RJS6AQX6KHrK1o2uw==',
privKey: '080012a609308204a20201000282010100b648aa3f1cc1597819a5d401775e28f3af1adf417749ce378f05901b771a8a47531cea3b911d78a3e875d83e3940934d41845d52dcb9782f08b47001e18207f8e7bb0c839e545b278629e52fd2e720bc2a41c25479710d36d22d0c8338cf58e2d6ab5aedbd26cd7008b6644567ebe43611c1e8df052f591b4b78acfe0d94997f0d8f1030be0c63c93e5edff20ef3979e98ca69a6cc7f658992cdaf383faa2768914bf9bb5a5d1ab7292ee3cd79338393472a281f8e51bb8a8fd1928581020848dac9b24397ddbbea86a52fd82106d49e12fdb492e81ab53bd8cb9f74c05949924bf297e9cfc481f410460c28af5745696ef57627a127dba22c1cbfc3374a5b2302030100010282010066d8eefdb70abca14fcf49a41e2689729c9ccbd4932a9868ae9093f37b2b055422e7d09d154e8c8fe68bff1b749023cc562809c3c3f7fd808427d27ead2f01b28584fb159412c26fb57a13eefccf1da02d337722d4765ddf4d8ccf5f86812f04a5dc7eec5e69f345c014b0d49c42f33b329fb6f58666659f49e0e7b25c1538d90bff5540cf02b2ec27ba864e12c5113b976344d8e9254873b30865357fbf19cd560a4a74b9020f58ac68ce0264ce5c36ca34a37fa88a2b010d5ba2fcc6a02c31de21886ad40a14ec72542c8ed4fb09613ec93be9196e105645113e2fb97ea693c447d6dd2c5c6cd6de42aca734efc87ec2e52bd394b53f52635e4ebca64dfe9102818100de2bc011d75dfbdccce26fabb3a631b380d44ccdd60db84c568f1cb1033cf9dcd011ef3acf1ef5ef7c8aa30d270b27835c44ed9375d85701f66838f547e64e0f24728b04f2ae5d9a56968a24080c84358efe3dde794bcafe6be32eb2b31a8183658dbe566d54e037c7207698a6f656db20596937a4996958cb40bdc9f13587eb02818100d20a1cc8b64a965f5d4236cb49f73272504db423b2eba720493601b582dbf3dd93144029f73f1c47b50ccdf67d4fd2649262cfa304a3eea12c982edd70c1ed74fe5a602f8ae4296537fe6d4ccadd2dbde27d59ca8787ab737006dbfdf5e95054ffa384960e299690f92e09bfbc8ffff6ca25e4d1afd3d9fdfacca32e66fba3a90281802e81ec10100c6d87d81fe28e87e9d767a3254dfa9cbf7c800672a8e7e92c9f8578ccf84e504343ea6120c8671d70395247436a943ecc0dd2ac593eeb21a4f55c381dfe3a07ef364af3ab49b9a731af8f62a29822f533478820df8acbffb021c276c4c83e615eae1d1f030db080eafa5d9e94f8f09bf53d57481d025dbeaf9d070281802edb0aa8cbe1bfc1ee7003013eb2e29215cfffcba6f2630a14caf37ea67ea2dc5f1f39612342f4f01a378d0adbd19ec1c8d63a33c7a93a66c22800ec6d6715adefc0018d1992e4992bf09a397357fc084c2a628987ca8038f458d362c8251042a5f4b873311d9df521615fd362214d9ca463e7b3cf619753cd4b316bfc954e610281806beec9501236f93a79f99999c60e1fbbd81c4b35d83006484ed0e09da5d212aa4d05d0fc5bcb6d8314e297644a62c88f5760fd42f303e226c4a11a6db213004f5979ebad9356733695b826d71eb664590a200431b71c65cd754e0c0160b28989728a7201a4fa68009652ce918b9966cc5a1dbcf91252e80417e8a1eb2b5a36bb',
pubKey: '080012a60230820122300d06092a864886f70d01010105000382010f003082010a0282010100b648aa3f1cc1597819a5d401775e28f3af1adf417749ce378f05901b771a8a47531cea3b911d78a3e875d83e3940934d41845d52dcb9782f08b47001e18207f8e7bb0c839e545b278629e52fd2e720bc2a41c25479710d36d22d0c8338cf58e2d6ab5aedbd26cd7008b6644567ebe43611c1e8df052f591b4b78acfe0d94997f0d8f1030be0c63c93e5edff20ef3979e98ca69a6cc7f658992cdaf383faa2768914bf9bb5a5d1ab7292ee3cd79338393472a281f8e51bb8a8fd1928581020848dac9b24397ddbbea86a52fd82106d49e12fdb492e81ab53bd8cb9f74c05949924bf297e9cfc481f410460c28af5745696ef57627a127dba22c1cbfc3374a5b230203010001'
}
expect(out.id).to.equal(expected.id)
expect(out.privKey).to.equal(expected.privKey)
expect(out.pubKey).to.equal(expected.pubKey)
done()
})
it('toBytes', (done) => {
it('toBytes', () => {
const id = PeerId.createFromHexString(testIdHex)
expect(id.toBytes().toString('hex')).to.equal(testIdBytes.toString('hex'))
done()
})
it('toJSON', (done) => {
const id = PeerId.create()
expect(id.toB58String()).to.equal(PeerId.createFromJSON(id.toJSON()).toB58String())
expect(id.privKey).to.deep.equal(PeerId.createFromJSON(id.toJSON()).privKey)
expect(id.pubKey).to.deep.equal(PeerId.createFromJSON(id.toJSON()).pubKey)
done()
describe('toJSON', () => {
it('full node', () => {
const id = PeerId.create({bits: 64})
expect(
id.toB58String()
).to.equal(
PeerId.createFromJSON(id.toJSON()).toB58String()
)
expect(
id.privKey.bytes
).to.deep.equal(
PeerId.createFromJSON(id.toJSON()).privKey.bytes
)
expect(
id.pubKey.bytes
).to.deep.equal(
PeerId.createFromJSON(id.toJSON()).pubKey.bytes
)
})
it('only id', () => {
const key = crypto.generateKeyPair('RSA', 64)
const id = PeerId.createFromBytes(key.public.hash())
expect(
id.toB58String()
).to.equal(
PeerId.createFromJSON(id.toJSON()).toB58String()
)
expect(id.privKey).to.not.exist
expect(id.pubKey).to.not.exist
})
})
describe('throws on inconsistent data', () => {
const k1 = crypto.generateKeyPair('RSA', 64)
const k2 = crypto.generateKeyPair('RSA', 64)
const k3 = crypto.generateKeyPair('RSA', 64)
it('missmatch id - private key', () => {
expect(
() => new PeerId(k1.public.hash(), k2)
).to.throw(
/inconsistent arguments/
)
})
it('missmatch id - public key', () => {
expect(
() => new PeerId(k1.public.hash(), null, k2.public)
).to.throw(
/inconsistent arguments/
)
})
it('missmatch private - public key', () => {
expect(
() => new PeerId(k1.public.hash(), k1, k2.public)
).to.throw(
/inconsistent arguments/
)
})
it('missmatch id - private - public key', () => {
expect(
() => new PeerId(k1.public.hash(), k1, k3.public)
).to.throw(
/inconsistent arguments/
)
})
it('invalid id', () => {
expect(
() => new PeerId(k1.public.hash().toString())
).to.throw(
/invalid id/
)
})
})
})