/* * Id is an object representation of a peer Id. a peer Id is a multihash */ var multihashing = require('multihashing') var base58 = require('bs58') var keypair = require('keypair') var forge = require('node-forge') exports = module.exports = Id exports.Buffer = Buffer function Id (id, privKey, pubKey) { var self = this if (!(self instanceof Id)) { throw new Error('Id must be called with new') } self.privKey = privKey self.pubKey = pubKey self.id = id // multihash - sha256 - buffer // pretty print self.toPrint = function () { return { id: self.toHexString(), privKey: privKey.toString('hex'), pubKey: pubKey.toString('hex') } } // encode/decode functions self.toHexString = function () { return self.id.toString('hex') } self.toBytes = function () { return self.id } self.toB58String = function () { return base58.encode(self.id) } } function fix (str) { return str.replace(/\r/g, '') + '\n' } // generation exports.create = function () { var pair = keypair() var mhId = multihashing(pair.public, 'sha2-256') return new Id(mhId, pair.private, pair.public) } exports.createFromHexString = function (str) { return new Id(new Buffer(str), 'hex') } exports.createFromBytes = function (buf) { return new Id(buf) } exports.createFromB58String = function (str) { return new Id(new Buffer(base58.decode(str))) } exports.createFromPubKey = function (pubKey) { var mhId = multihashing(pubKey, 'sha2-256') return new Id(mhId, null, pubKey) } exports.createFromPrivKey = function (privKey) { var privateKey = forge.pki.privateKeyFromPem(privKey) var publicKey = { n: privateKey.n, e: privateKey.e } var pubKey = fix(forge.pki.publicKeyToRSAPublicKeyPem(publicKey, 72)) var mhId = multihashing(pubKey, 'sha2-256') return new Id(mhId, privKey, pubKey) }